###
#Replication File for "The Spoils of Victory: Campaign Donations and Government Contracts in Brazil"
###
#To replicate plots and tables, change working  below to directory containing replication data "spoils_of_victory_replication_data.RData" 
#Plots will be saved in PDF format; tables will be saved in tex files that can be pasted into a latex document. Note: to compile the latex tables, the "ctable" package is necessary. 

#Ran on R 3.0.2
set.seed(1222013305)
load("spoils_of_victory_replication_data.RData")

#The following R packages are required
library(Hmisc)
library(ggplot2)
library(reshape)
library(AER)
library(grid)
library(plyr)

options(warn = -1)


#Function to get heteroskedastically robust SE
summaryR.lm <- function(model, type=c("hc3", "hc0", "hc1", "hc2", "hc4"), ...){
  if (!require(car)) stop("Required car package is missing.")
  type <- match.arg(type)
  V <- hccm(model, type=type)
  sumry <- summary(model)
  table <- coef(sumry)
  table[,2] <- sqrt(diag(V))
  table[,3] <- table[,1]/table[,2]
  table[,4] <- 2*pt(abs(table[,3]), df.residual(model), lower.tail=FALSE)
  sumry$coefficients <- table
  p <- nrow(table)
  hyp <- cbind(0, diag(p - 1))
  sumry
}

reais.format <- function(x){
  paste("R\\$", prettyNum(round(x), big.mark = ","), sep =" ")
}

#Function for making discontinuity plots
discont.plot <- function(y, force.var, cluster, treat,  span = .7, n.boots = 100, bins = 25, xlab = "Forcing Variable", ylab = "Outcome", title="", degree = degree){
  data <- data.frame(y=y, force.var = force.var, cluster.id = cluster, treat = treat)
  clusters <- unique(cluster)
  for(i in 1:n.boots){
    bs.clusters <- data.frame(cluster.id=sample(clusters, replace=TRUE))
    bs.data <- merge(bs.clusters, data,all.x=TRUE,all.y=FALSE, by.x="cluster.id", by.y="cluster.id")
    lo.treat <- loess(y~force.var, data = bs.data[bs.data$treat==1,], span=span, surface="direct", degree = degree)
    lo.control <- loess(y~force.var, data = bs.data[bs.data$treat==0,], span=span, surface="direct", degree = degree)
    lo.fit.treat <- predict(lo.treat, newdata = data$force.var[data$treat==1])
    lo.fit.control <- predict(lo.control, newdata = data$force.var[data$treat==0])
    if(i ==1){
      lo.treat.bs <- matrix(nrow=length(lo.fit.treat), ncol = n.boots)
      lo.control.bs <- matrix(nrow=length(lo.fit.control), ncol = n.boots)
    }
    lo.treat.bs[,i] <- lo.fit.treat
    lo.control.bs[,i] <- lo.fit.control
    if( i %% (0.1 * n.boots) == 0) {  # output progress for each p
      cat(".")
    }
  }
  lo.treat <- loess(y~force.var, data = data[data$treat==1,], span=span, surface="direct", degree = degree)
  lo.control <- loess(y~force.var, data = data[data$treat==0,], span=span, surface="direct", degree = degree)
  lo.fit.treat <- predict(lo.treat, newdata = data$force.var[data$treat==1])
  lo.fit.control <- predict(lo.control, newdata = data$force.var[data$treat==0])
  lo.results.treat <- data.frame(force.var = data$force.var[data$treat==1], y = data$y[data$treat==1], y.fit = lo.fit.treat, conf.hi =  apply(lo.treat.bs,1,quantile,probs=c(.025)), conf.lo =  apply(lo.treat.bs,1,quantile,probs=c(.975)),treat=1)
  lo.results.treat$bin <- sapply(strsplit(gsub("^\\W|\\W$", "", cut(lo.results.treat$force.var, breaks = bins)), ","), function(x)sum(as.numeric(x))/2)
  lo.results.treat <- ddply(lo.results.treat, .(bin), transform, bin.mean = mean(y)) 
  lo.results.control <- data.frame(force.var = data$force.var[data$treat==0], y = data$y[data$treat==0], y.fit = lo.fit.control, conf.hi =  apply(lo.control.bs,1,quantile,probs=c(.025)), conf.lo =  apply(lo.control.bs,1,quantile,probs=c(.975)),treat=0)
  lo.results.control$bin <- sapply(strsplit(gsub("^\\W|\\W$", "", cut(lo.results.control$force.var, breaks = bins)), ","), function(x)sum(as.numeric(x))/2)
  lo.results.control <- ddply(lo.results.control, .(bin), transform, bin.mean = mean(y))
  lo.results <- rbind(lo.results.treat, lo.results.control)
  lo.results$treat <- as.factor(lo.results$treat)
  ggplot(lo.results, aes(x=force.var, y = y.fit, group=treat, color = treat)) + geom_line(aes(y=y.fit), size=1.5)  + geom_vline(xintercept=0) + geom_ribbon(aes(ymin = conf.hi, ymax=conf.lo), alpha =.2)  + geom_point(aes(x=bin, y=bin.mean)) + theme_bw()   + theme(legend.position = "none")  + scale_colour_brewer(palette="Set1")  + scale_x_continuous(xlab) +  scale_y_continuous(ylab) + labs(title = title) + theme(axis.title.x = element_text(vjust = .3)) + theme(plot.title = element_text(size = rel(.9)))
}


#Functions for estimating treatment effects using loess
boot.loess <- function(data, index, span = .75, degree = 2){
  boot.data <- data[index,]
  lo.treat <- loess(y~force.var, data = boot.data[boot.data$treat==1,], span=span, surface="direct", degree = degree)
  lo.cont <- loess(y~force.var, data = boot.data[boot.data$treat==0,], span=span, surface="direct", degree = degree)
  lo.fit.tr <- predict(lo.treat, newdata = 0, se = TRUE)
  lo.fit.co <- predict(lo.cont, newdata = 0, se = TRUE)
  c(lo.fit.tr$fit-lo.fit.co$fit, var.t = lo.fit.tr$se.fit + lo.fit.co$se.fit)
}

lo.ate <- function(y, treat, force.var, span = 1, R = 500, degree = 2, replicates = FALSE){
  library(boot)
  data <- data.frame(y, treat, force.var)
  boot.out <- boot(data = data, span = span, statistic = boot.loess, R  = R)
  ci.out <- boot.ci(boot.out, type = "stud")
  lo.treat <- loess(y~force.var, data = data[data$treat==1,], span=span, surface="direct", degree = degree)
  lo.cont <- loess(y~force.var, data = data[data$treat==0,], span=span, surface="direct", degree = degree)
  lo.fit.tr <- predict(lo.treat, newdata = 0)
  lo.fit.co <- predict(lo.cont, newdata = 0)
  if(replicates == TRUE){
    list(est = lo.fit.tr - lo.fit.co, se = sd(boot.out$t[,1]), conf.int = c(ci.out$student[4], ci.out$student[5]), tr.est = lo.fit.tr, con.est = lo.fit.co, boot.replicates = boot.out$t[,1])
  }
  else{
    list(est = lo.fit.tr - lo.fit.co, se = sd(boot.out$t[,1]), conf.int = c(ci.out$student[4], ci.out$student[5]), tr.est = lo.fit.tr, con.est = lo.fit.co)    
  }
}


#Function for the McCrary Density Test
mccrary.test <- function(force.var, h = .75, n.boots = 1000){
  ##Note that this function assumes that the discontinuity is at 0
  force.below <-force.var[force.var<0]
  force.below <- force.below[force.below>=quantile(force.below, prob=.1)]
  force.above <-force.var[force.var>0]
  force.above <- force.above[force.above<=quantile(force.above, prob=.9)]
  bin.width <- 2 * sd(c(force.above,force.below)) * 1/sqrt(length(c(force.below,force.above)))
  force.below.bin <-  data.frame(table(cut(force.below, breaks = seq(0, min(force.below), by=-1*bin.width ))))
  force.above.bin <- data.frame(table(cut(force.above, breaks = seq(0, max(force.above), by=bin.width ))))
  force.below.bin$Var1 <- sapply(strsplit(gsub("^\\W|\\W$", "", force.below.bin$Var1), ","), function(x)sum(as.numeric(x))/2)
  force.above.bin$Var1 <- sapply(strsplit(gsub("^\\W|\\W$", "", force.above.bin$Var1), ","), function(x)sum(as.numeric(x))/2)
  bin.freq <- rbind(force.below.bin, force.above.bin)
  lo.fit.above <- loess(Freq~Var1, data = bin.freq[bin.freq$Var1>0,], degree=1,span = h)
  lo.fit.below <- loess(Freq~Var1, data = bin.freq[bin.freq$Var1<0,], degree=1,span = h)
  lo.predict <- rbind(data.frame(bin.mid = bin.freq$Var1[bin.freq$Var1<0],  pred.dens = predict(lo.fit.below)),data.frame(bin.mid = bin.freq$Var1[bin.freq$Var1>0],  pred.dens = predict(lo.fit.above)))
  wald.stat <- log(predict(loess(pred.dens~bin.mid, data=lo.predict[lo.predict$bin.mid<0,],span=h,degree=1, surface="direct") ,newdata=data.frame(bin.mid=0))) - log(predict(loess(pred.dens~bin.mid, data=lo.predict[lo.predict$bin.mid>0,],span=h,degree=1, surface="direct") ,newdata=data.frame(bin.mid=0)))
  
  #use the bootstrap to calculate standard error
  log.dis.bs <- matrix(nrow = n.boots)
  for(i in 1:n.boots){
    force.above.bs <- force.above[sample(1:length(force.above), replace = TRUE)]
    force.below.bs <- force.below[sample(1:length(force.below), replace = TRUE)]
    force.below.bs <- force.below.bs[force.below.bs>=quantile(force.below.bs, prob=.1)]
    force.above.bs <- force.above.bs[force.above.bs<=quantile(force.above.bs, prob=.9)]
    bin.width <- 2 * sd(c(force.above.bs,force.below.bs)) * 1/sqrt(length(c(force.below.bs, force.above.bs)))
    force.below.bin <-  data.frame(table(cut(force.below.bs, breaks = seq(0, min(force.below.bs), by=-1*bin.width ))))
    force.above.bin <- data.frame(table(cut(force.above.bs, breaks = seq(0, max(force.above.bs), by=bin.width ))))
    force.below.bin$Var1 <- sapply(strsplit(gsub("^\\W|\\W$", "", force.below.bin$Var1), ","), function(x)sum(as.numeric(x))/2)
    force.above.bin$Var1 <- sapply(strsplit(gsub("^\\W|\\W$", "", force.above.bin$Var1), ","), function(x)sum(as.numeric(x))/2)
    bin.freq <- rbind(force.below.bin, force.above.bin)
    lo.fit.above <- loess(Freq~Var1, data = bin.freq[bin.freq$Var1>0,], degree=1,span = h)
    lo.fit.below <- loess(Freq~Var1, data = bin.freq[bin.freq$Var1<0,], degree=1,span = h)
    lo.predict <- rbind(data.frame(bin.mid = bin.freq$Var1[bin.freq$Var1<0],  pred.dens = predict(lo.fit.below)),data.frame(bin.mid = bin.freq$Var1[bin.freq$Var1>0],  pred.dens = predict(lo.fit.above)))
    
    log.dis.bs[i] <- log(predict(loess(pred.dens~bin.mid, data=lo.predict[lo.predict$bin.mid<0,],span=h,degree=1, surface="direct") ,newdata=data.frame(bin.mid=0))) - log(predict(loess(pred.dens~bin.mid, data=lo.predict[lo.predict$bin.mid>0,],span=h,degree=1, surface="direct") ,newdata=data.frame(bin.mid=0)))
  }
  list(wald.stat = wald.stat, se = sd(log.dis.bs, na.rm = TRUE))  
}


#Number of bootstrap samples
num.boots <- 1000

#Set tuning parameters for loess estimator
span <- 1
lo.degree <- 1

###
#Datasets for the various samples
###
depfed_data$incumbent <- depfed.balance$incumbent
depfed_data$uf.sp <- ifelse(depfed_data$uf == "SP", 1, 0)
depfed_data$uf.mg <- ifelse(depfed_data$uf == "MG", 1, 0)
##Loess Data, Estimation Samples
lo.bw <- 40000
lo.all.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$donations>0,]
lo.all.pw.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$pw.donations>0,]
lo.coal.pw.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Loess Data, Balance Samples
lo.all.baldata <- depfed.balance[abs(depfed.balance$votemargin)<lo.bw & depfed.balance$donations>0,]
lo.all.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin)<lo.bw & depfed.balance$pw.donations>0,]
lo.coal.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin)<lo.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin)<lo.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]

###Local Linear Bandwidth
ll.bw <- 25000
##Local Linear Data, Estimation Samples
ll.all.data <- depfed_data[abs(depfed_data$votemargin) < ll.bw & depfed_data$donations > 0,]
ll.all.pw.data <- depfed_data[abs(depfed_data$votemargin)<ll.bw & depfed_data$pw.donations>0,]
ll.coal.pw.data <- depfed_data[abs(depfed_data$votemargin)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.data <- depfed_data[abs(depfed_data$votemargin)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Local Linear Data, Balance Samples
ll.all.baldata <- depfed.balance[abs(depfed.balance$votemargin) < ll.bw & depfed.balance$donations > 0,]
ll.all.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin)<ll.bw & depfed.balance$pw.donations>0,]
ll.coal.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin)<ll.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin)<ll.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]



##Polynomial Data, Estimation Samples
poly.order <- 3
ply.bw <- 100000
ply.all.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$donations > 0,]
ply.all.pw.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$pw.donations>0,]
ply.coal.pw.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Polynomial Data, Balance Samples
ply.all.baldata <- depfed.balance[abs(depfed.balance$votemargin) < ply.bw & depfed.balance$donations > 0,]
ply.all.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin) < ply.bw & depfed.balance$pw.donations>0,]
ply.coal.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin) < ply.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.baldata <- depfed.balance[abs(depfed.balance$votemargin) < ply.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]

#####
##Figure 1: Balance Tests
#####
bal.var <- c("coalvotes", "incumbent", "contracts.0406", "pw.con.0406", "donations", "pw.donations", "donor.firms", "pw.donor.firms", "year.opened", "commerce", "manufacture", "financial", "cand.uf.sp", "cand.uf.mg", "cand.uf.rs", "cand.uf.ba", "cand.uf.rj", "party.psdb", "party.pfl", "party.pt", "party.pmdb", "superior.edu", "occ.pol", "yob", "individ.donations", "occ.business", "coalvotes", "individual.donors", "coalseats", "agriculture", "numb.company.recipients", "total.company.donations", "totalDonations.winners.firm", "winners.donated.to")


lo.bal <- list()
lo.bal$all <- list()
lo.bal$all.pw <- list()
lo.bal$coal.pw <- list()
lo.bal$pt.pw <- list()

ll.bal <- list()
ll.bal$all <- list()
ll.bal$all.pw <- list()
ll.bal$coal.pw <- list()
ll.bal$pt.pw <- list()
length(ll.bal$pt.pw) <- length(bal.var)

ply.bal <- list()
ply.bal$all <- list()
ply.bal$all.pw <- list()
ply.bal$coal.pw <- list()
ply.bal$pt.pw <- list()
length(ply.bal$pt.pw) <- length(bal.var)

for(i in 1:length(bal.var)){
  print(paste("Checking Balance on", bal.var[i]))
  lo.bal$all[[i]] <- with(lo.all.baldata, lo.ate(y = lo.all.baldata[ , bal.var[i]], treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
  lo.bal$all[[i]]$sd <- (sd(lo.all.baldata[lo.all.baldata$elected == 1 , bal.var[i]]) + sd(lo.all.baldata[lo.all.baldata$elected == 0 , bal.var[i]])) / 2
  names(lo.bal$all)[i] <- bal.var[i]
  
  lo.bal$all.pw[[i]] <- with(lo.all.pw.baldata, lo.ate(y = lo.all.pw.baldata[, bal.var[i]], treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
  lo.bal$all.pw[[i]]$sd <- (sd(lo.all.pw.baldata[lo.all.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.all.pw.baldata[lo.all.pw.baldata$elected == 0 , bal.var[i]])) / 2
  names(lo.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(lo.coal.pw.baldata[ , bal.var[i]])) == 1){
    lo.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(lo.coal.pw.baldata[ , bal.var[i]])) > 1){
    lo.bal$coal.pw[[i]] <- with(lo.coal.pw.baldata, lo.ate(y = lo.coal.pw.baldata[, bal.var[i]], treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
    lo.bal$coal.pw[[i]]$sd <- (sd(lo.coal.pw.baldata[lo.coal.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.coal.pw.baldata[lo.coal.pw.baldata$elected == 0 , bal.var[i]])) / 2  
  }
  names(lo.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(lo.pt.pw.baldata[ , bal.var[i]])) == 1){
    lo.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(lo.pt.pw.baldata[ , bal.var[i]])) > 1){
    lo.bal$pt.pw[[i]] <- with(lo.pt.pw.baldata, lo.ate(y = lo.pt.pw.baldata[, bal.var[i]], treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
    lo.bal$pt.pw[[i]]$sd <- (sd(lo.pt.pw.baldata[lo.pt.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.pt.pw.baldata[lo.pt.pw.baldata$elected == 0 , bal.var[i]])) / 2
  }
  names(lo.bal$pt.pw)[i] <- bal.var[i]
  
  ll.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*votemargin")) , data = ll.all.baldata), type = "hc2")
  ll.bal$all[[i]]$sd <- (sd(ll.all.baldata[ll.all.baldata$elected == 1, bal.var[i]]) + sd(ll.all.baldata[ll.all.baldata$elected == 0, bal.var[i]])) / 2
  names(ll.bal$all)[i] <- bal.var[i]
  
  ll.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*votemargin")) , data = ll.all.pw.baldata), type = "hc2")
  ll.bal$all.pw[[i]]$sd <- (sd(ll.all.pw.baldata[ll.all.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.all.pw.baldata[ll.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(ll.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(ll.coal.pw.baldata[ , bal.var[i]])) == 1){
    ll.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(ll.coal.pw.baldata[ , bal.var[i]])) > 1){
    ll.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*votemargin")) , data = ll.coal.pw.baldata), type = "hc2")
    ll.bal$coal.pw[[i]]$sd <- (sd(ll.coal.pw.baldata[ll.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.coal.pw.baldata[ll.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(ll.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(ll.pt.pw.baldata[ , bal.var[i]])) == 1){
    ll.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(ll.pt.pw.baldata[ , bal.var[i]])) > 1){
    ll.bal$pt.pw[[i]] <- tryCatch(summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*votemargin")) , data = ll.pt.pw.baldata), type = "hc2"), error = function(e) NA)
    if(is.na(ll.bal$pt.pw[[i]][1]) == FALSE){
      ll.bal$pt.pw[[i]]$sd <- (sd(ll.pt.pw.baldata[ll.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.pt.pw.baldata[ll.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
    }
  }
  names(ll.bal$pt.pw)[i] <- bal.var[i]  
  ply.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.all.baldata), type = "hc2")
  ply.bal$all[[i]]$sd <- (sd(ply.all.baldata[ply.all.baldata$elected == 1, bal.var[i]]) + sd(ply.all.baldata[ply.all.baldata$elected == 0, bal.var[i]])) / 2
  names(ply.bal$all)[i] <- bal.var[i]
  
  ply.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.all.pw.baldata), type = "hc2")
  ply.bal$all.pw[[i]]$sd <- (sd(ply.all.pw.baldata[ply.all.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.all.pw.baldata[ply.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(ply.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(ply.coal.pw.baldata[ , bal.var[i]])) == 1){
    ply.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(ply.coal.pw.baldata[ , bal.var[i]])) > 1){
    ply.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.baldata), type = "hc2")
    ply.bal$coal.pw[[i]]$sd <- (sd(ply.coal.pw.baldata[ply.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.coal.pw.baldata[ply.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(ply.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(ply.pt.pw.baldata[ , bal.var[i]])) == 1){
    ply.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(ply.pt.pw.baldata[ , bal.var[i]])) > 1){
    ply.bal$pt.pw[[i]] <- tryCatch(summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.baldata), type = "hc2"), error = function(e) NA)
    if(is.na(ply.bal$pt.pw[[i]][1]) == FALSE){
      ply.bal$pt.pw[[i]]$sd <- (sd(ply.pt.pw.baldata[ply.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.pt.pw.baldata[ply.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
    }
  }
  names(ply.bal$pt.pw)[i] <- bal.var[i]
  
}

lo.bal <- lapply(lo.bal, function(x){x[is.na(x)] <- NULL; x})
ll.bal <- lapply(ll.bal, function(x){x[is.na(x)] <- NULL; x})
ply.bal <- lapply(ply.bal, function(x){x[is.na(x)] <- NULL; x})
std.diff.table <- data.frame(Estimate = c(
  ldply(lo.bal, function(x) ldply(x, function(x) x$est))$V1,
  ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1,
  ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1),
                             SD = c(
                               ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$V1,
                               ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$V1,
                               ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$V1),
                             Variable = c(
                               ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$.id,
                               ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$.id,
                               ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$.id),  
                             Sample = c(rep(c("All", "Public Works", "Public Works, Coalition", "Public Works, PT"), sapply(lo.bal, length)), 
                                        rep(c("All", "Public Works", "Public Works, Coalition", "Public Works, PT"), 
                                            sapply(ply.bal, length)),
                                        rep(c("All", "Public Works", "Public Works, Coalition", "Public Works, PT"), sapply(ll.bal, length))
                             ),
                             Estimator = c(
                               rep("Loess", sum(sapply(lo.bal, length))), 
                               rep("Polynomial", sum(sapply(ply.bal, length))), rep("Local Linear", sum(sapply(ll.bal, length))))
)
std.diff.table$std.diff <- std.diff.table$Estimate / std.diff.table$SD
std.diff.table$Variable <- reorder(std.diff.table$Variable, std.diff.table$std.diff, mean)

tstat.table <- data.frame(Estimate = c(
  ldply(lo.bal, function(x) ldply(x, function(x) x$est))$V1,
  ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1,
  ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1),
                          SE = c(
                            ldply(lo.bal, function(x) ldply(x, function(x) x$se))$V1,
                            ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,2]))$V1,
                            ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,2]))$V1),
                          Variable = c(
                            ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$.id,
                            ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$.id,
                            ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$.id),  
                          Sample = c(
                            rep(c("All", "Public Works", "Public Works, Coalition", "Public Works, PT"), sapply(lo.bal, length)), 
                            rep(c("All", "Public Works", "Public Works, Coalition", "Public Works, PT"), sapply(ply.bal, length)),
                            rep(c("All", "Public Works", "Public Works, Coalition", "Public Works, PT"), sapply(ll.bal, length))
                          ),
                          Estimator = c(
                            rep("Loess", sum(sapply(lo.bal, length))),
                            rep("Polynomial", sum(sapply(ply.bal, length))), rep("Local Linear", sum(sapply(ll.bal, length))))
)
tstat.table$tstat <- abs(tstat.table$Estimate / tstat.table$SE)
tstat.table$Variable <- reorder(tstat.table$Variable, tstat.table$tstat, max)

std.diff.table$Variable <- recode(std.diff.table$Variable, c("'coalvotes' = 'Coalition Votes'; 'yob' = 'Birth Year'; 'comm.donations' = 'Party Donations'; 'incumbent' = 'Incumbent'; 'contracts.0406' = 'Contracts (\\'04-\\'06)'; 'pw.con.0406' = 'Public Works Contracts (\\'04-\\'06)'; 'donations' = 'Total Donations Received'; 'pw.donations' = 'Public Works Donations Received'; 'donor.firms' = 'No. Donor Firms'; 'pw.donor.firms' = 'Percent Public Works Donors'; 'year.opened' = 'Mean Donor Year Founded'; 'commerce' = 'Percent Commerce Donors'; 'manufacture' = 'Percent Manufacturing Donors'; 'financial' = 'Percent Financial Donors'; 'agriculture' = 'Percent Agricultural Donors'; 'cand.uf.sp' = 'State - São Paulo'; 'cand.uf.mg' = 'State - Minas Gerais';  'cand.uf.rs' = 'State - Rio Grande do Sul'; 'superior.edu' = 'Higher Education'; 'occ.pol' = 'Occupation - Politician'; 'individ.donations' = 'Individual Donations'; 'numb.company.recipients' = 'Mean Donor No. Candidate Recipients'; 'party.pmdb' = 'Party - PMDB'; 'party.pfl' = 'Party - PFL'; 'total.company.donations' = 'Mean Donor Total Donations'; 'coalvotes' = 'Coalition Votes'; 'party.pt' = 'Party - PT'; 'party.psdb' = 'Party - PSDB'; 'occ.business' = 'Occupation - Business'; 'cand.uf.rj' = 'State - Rio de Janeiro'; 'cand.uf.ba' = 'State - Bahia'; 'coalseats' = 'Coalition Seats'; 'individual.donors' = 'No. Individual Donors'; 'totalDonations.winners.firm' = 'Mean Donor Donations to Winners'; 'winners.donated.to' = 'Mean Donor No. Winning Recipients'"))

tstat.table$Variable <- recode(tstat.table$Variable, c("'coalvotes' = 'Coalition Votes'; 'yob' = 'Birth Year'; 'comm.donations' = 'Party Donations'; 'incumbent' = 'Incumbent'; 'contracts.0406' = 'Contracts (\\'04-\\'06)'; 'pw.con.0406' = 'Public Works Contracts (\\'04-\\'06)'; 'donations' = 'Total Donations Received'; 'pw.donations' = 'Public Works Donations Received'; 'donor.firms' = 'Donor Firms'; 'pw.donor.firms' = 'Percent Public Works Donors'; 'year.opened' = 'Mean Donor Year Founded'; 'commerce' = 'Percent Commerce Donors'; 'manufacture' = 'Percent Manufacturing Donors'; 'financial' = 'Percent Financial Donors'; 'agriculture' = 'Percent Agricultural Donors'; 'cand.uf.sp' = 'State - São Paulo'; 'cand.uf.mg' = 'State - Minas Gerais';  'cand.uf.rs' = 'State - Rio Grande do Sul'; 'superior.edu' = 'Higher Education'; 'occ.pol' = 'Occupation - Politician'; 'individ.donations' = 'Individual Donations'; 'numb.company.recipients' = 'Mean Donor Candidate Recipients'; 'party.pmdb' = 'Party - PMDB'; 'party.pfl' = 'Party - PFL'; 'total.company.donations' = 'Mean Donor Total Donations'; 'coalvotes' = 'Coalition Votes'; 'party.pt' = 'Party - PT'; 'party.psdb' = 'Party - PSDB'; 'occ.business' = 'Occupation - Business'; 'cand.uf.rj' = 'State - Rio de Janeiro'; 'cand.uf.ba' = 'State - Bahia'; 'coalseats' = 'Coalition Seats'; 'individual.donors' = 'Individual Donors'; 'totalDonations.winners.firm' = 'Mean Donor Donations to Winners'; 'winners.donated.to' = 'Mean Donor Winning Recipients'"))

levels(std.diff.table$Sample) <- c("All", "Public Works", "Public Works, Coalition", "Public Works, PT")

levels(tstat.table$Sample) <- c("All", "Public Works", "Public Works, Coalition", "Public Works, PT")
pdf(file = "figure1.pdf", height = 6, width = 10)
ggplot(tstat.table, aes(x = tstat, y = Variable, shape = Sample, color = Sample)) + geom_point() + geom_vline(xintercept = 2, lty = 2, size = .2) + facet_grid(.~Estimator) + theme_bw() + scale_x_continuous("T Statistic") + scale_color_brewer(palette = "Set1") + opts(axis.title.x = theme_text(vjust = -0.3), title = "Balance Statistics for Federal Deputies")
dev.off()

###
#TABLE 1
###

###Loess Estimator
##All Donation Recipients
lo.all <-  with(lo.all.data, lo.ate(y = log((contracts.0810 + 1)/donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all$est.unlogged <- reais.format(exp(lo.all$tr.est) - exp(lo.all$con.est))
lo.all$num.donors <- with(lo.all.data, lo.ate(y = log(donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all$num.donors <- mean(exp(lo.all$num.donors$tr.est), exp(lo.all$num.donors$con.est))
lo.all$donations <- with(lo.all.data , lo.ate(y = log(donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all$donations <- reais.format(mean(exp(lo.all$donations$tr.est) , exp(lo.all$donations$con.est)) / lo.all$num.donors)
lo.all$N <- nrow(depfed_data[abs(depfed_data$votemargin) < lo.bw & depfed_data$donations>0,]) 

##Public Works, all
lo.all.pw <- with(lo.all.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$est.unlogged <- reais.format(exp(lo.all.pw$tr.est) - exp(lo.all.pw$con.est))
lo.all.pw$num.donors <- with(lo.all.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$num.donors <- mean(exp(lo.all.pw$num.donors$tr.est), exp(lo.all.pw$num.donors$con.est))
lo.all.pw$donations <- with(lo.all.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$donations <- reais.format(mean(exp(lo.all.pw$donations$tr.est) , exp(lo.all.pw$donations$con.est)) / lo.all.pw$num.donors)
lo.all.pw$N <- nrow(lo.all.pw.data)

##Public works, coalition
lo.coal.pw <- with(lo.coal.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$est.unlogged <- reais.format(exp(lo.coal.pw$tr.est) - exp(lo.coal.pw$con.est))
lo.coal.pw$num.donors <- with(lo.coal.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$num.donors <- mean(exp(lo.coal.pw$num.donors$tr.est), exp(lo.coal.pw$num.donors$con.est))
lo.coal.pw$donations <- with(lo.coal.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$donations <- reais.format(mean(exp(lo.coal.pw$donations$tr.est) , exp(lo.coal.pw$donations$con.est)) / lo.coal.pw$num.donors)
lo.coal.pw$N <- nrow(lo.coal.pw.data)

##Public works, PT
lo.pt.pw <- with(lo.pt.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$est.unlogged <- reais.format(exp(lo.pt.pw$tr.est) - exp(lo.pt.pw$con.est))
lo.pt.pw$num.donors <- with(lo.pt.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$num.donors <- mean(exp(lo.pt.pw$num.donors$tr.est), exp(lo.pt.pw$num.donors$con.est))
lo.pt.pw$donations <- with(lo.pt.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$donations <- reais.format(mean(exp(lo.pt.pw$donations$tr.est) , exp(lo.pt.pw$donations$con.est)) / lo.pt.pw$num.donors)
lo.pt.pw$N <- nrow(lo.pt.pw.data)


###Local Linear
##All candidates
ll.all <- summaryR.lm(lm(log((contracts.0810 + 1)/donor.firms) ~ elected*votemargin, data = ll.all.data), type = "hc2")
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summaryR.lm(lm(log(donor.firms) ~ elected*votemargin , data = ll.all.data), type = "hc2")
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summaryR.lm(lm(log(donations) ~ elected*votemargin , data = ll.all.data), type = "hc2")
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.all.pw.data), type = "hc2")
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

##All candidates
ply.all <- summaryR.lm(lm(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))   , data = ply.all.data))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summaryR.lm(lm(as.formula(paste("log(donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summaryR.lm(lm(as.formula(paste("log((donations)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data)

##Public works
ply.all.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.data))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data)

#Gather all results into one table
raw.results.table <- data.frame(cbind(
  round(c(lo.all$est, lo.all.pw$est, lo.coal.pw$est, lo.pt.pw$est, ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(lo.all$se, lo.all.pw$se, lo.coal.pw$se, lo.pt.pw$se, ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c(lo.all$est.unlogged, lo.all.pw$est.unlogged, lo.coal.pw$est.unlogged, lo.pt.pw$est.unlogged, ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c(lo.all$donations, lo.all.pw$donations, lo.coal.pw$donations, lo.pt.pw$donations, ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(lo.all$N, lo.all.pw$N, lo.coal.pw$N, lo.pt.pw$N, ply.all$N, ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(raw.results.table) <- c("$\\tau_{RD}$", "Standard Error", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010. ``PT'' candidates are those from the ruling Worker's Party. ``Coalition'' candidates are those from the parties listed in footnote 12. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity.  The loess specification uses a bandwidth of ", prettyNum(lo.bw, big.mark = ",", scientific = FALSE), " votes and a span of ", span, ". The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " votes, respectively.  Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

#Note: The following command creates a latex table that can only be compiled when using the "ctable" latex package. 
#Note: The results in this latex table correspond to the results in the left half of Table 1 
raw.results.table.latex <- latex(raw.results.table, cdec = c(2, 2, 0, 0, 0), file = "table1_all_contracts.tex", col.just = rep("c", 5), rowname = c("All", "Public works donations", "Public works, coalition", "Public works, PT", "All", "Public works donations", "Public works, coalition", "Public works, PT", "All", "Public works donations", "Public works, coalition", "Public works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts", insert.bottom = bottom.note, rgroup = c("Loess Estimator", "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")

##DNIT Analysis

###Loess Estimator
##All Donation Recipients
lo.all <-  with(lo.all.data[lo.all.data$donations > 0,], lo.ate(y = log((contracts.dnit.0810 + 1)/donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all$est.unlogged <- reais.format(exp(lo.all$tr.est) - exp(lo.all$con.est))
lo.all$num.donors <- with(lo.all.data[lo.all.data$donations > 0, ], lo.ate(y = log(donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all$num.donors <- mean(exp(lo.all$num.donors$tr.est), exp(lo.all$num.donors$con.est))
lo.all$donations <- with(lo.all.data[lo.all.data$donations > 0, ] , lo.ate(y = log(donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all$donations <- reais.format(mean(exp(lo.all$donations$tr.est) , exp(lo.all$donations$con.est)) / lo.all$num.donors)
lo.all$N <- nrow(depfed_data[abs(depfed_data$votemargin) < lo.bw  & depfed_data$donations > 0,]) 

##Public Works, all
lo.all.pw <- with(lo.all.pw.data[lo.all.pw.data$pw.donations > 0, ], lo.ate(y = log((pwcontracts.dnit.0810 + 1)/pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$est.unlogged <- reais.format(exp(lo.all.pw$tr.est) - exp(lo.all.pw$con.est))
lo.all.pw$num.donors <- with(lo.all.pw.data[lo.all.pw.data$pw.donations > 0, ], lo.ate(y = log(pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$num.donors <- mean(exp(lo.all.pw$num.donors$tr.est), exp(lo.all.pw$num.donors$con.est))
lo.all.pw$donations <- with(lo.all.pw.data[lo.all.pw.data$pw.donations > 0, ] , lo.ate(y = log(pw.donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$donations <- reais.format(mean(exp(lo.all.pw$donations$tr.est) , exp(lo.all.pw$donations$con.est)) / lo.all.pw$num.donors)
lo.all.pw$N <- nrow(lo.all.pw.data[lo.all.pw.data$pw.donations > 0, ])

##Public works, coalition
lo.coal.pw <- with(lo.coal.pw.data[lo.coal.pw.data$pw.donations > 0, ], lo.ate(y = log((pwcontracts.dnit.0810 + 1)/pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$est.unlogged <- reais.format(exp(lo.coal.pw$tr.est) - exp(lo.coal.pw$con.est))
lo.coal.pw$num.donors <- with(lo.coal.pw.data[lo.coal.pw.data$pw.donations > 0, ], lo.ate(y = log(pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$num.donors <- mean(exp(lo.coal.pw$num.donors$tr.est), exp(lo.coal.pw$num.donors$con.est))
lo.coal.pw$donations <- with(lo.coal.pw.data[lo.coal.pw.data$pw.donations > 0, ] , lo.ate(y = log(pw.donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$donations <- reais.format(mean(exp(lo.coal.pw$donations$tr.est) , exp(lo.coal.pw$donations$con.est)) / lo.coal.pw$num.donors)
lo.coal.pw$N <- nrow(lo.coal.pw.data)

##Public works, PT
lo.pt.pw <- with(lo.pt.pw.data[lo.pt.pw.data$pw.donations > 0 , ], lo.ate(y = log((pwcontracts.dnit.0810 + 1)/pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$est.unlogged <- reais.format(exp(lo.pt.pw$tr.est) - exp(lo.pt.pw$con.est))
lo.pt.pw$num.donors <- with(lo.pt.pw.data[lo.pt.pw.data$pw.donations > 0 , ], lo.ate(y = log(pw.donor.firms), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$num.donors <- mean(exp(lo.pt.pw$num.donors$tr.est), exp(lo.pt.pw$num.donors$con.est))
lo.pt.pw$donations <- with(lo.pt.pw.data[lo.pt.pw.data$pw.donations > 0 , ] , lo.ate(y = log(pw.donations), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$donations <- reais.format(mean(exp(lo.pt.pw$donations$tr.est) , exp(lo.pt.pw$donations$con.est)) / lo.pt.pw$num.donors)
lo.pt.pw$N <- nrow(lo.pt.pw.data)

###Local Linear
##All candidates
ll.all <- summaryR.lm(lm(log((contracts.dnit.0810 + 1)/donor.firms) ~ elected*votemargin, data = ll.all.data[ll.all.data$donations > 0, ]), type = "hc2")
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summaryR.lm(lm(log(donor.firms) ~ elected*votemargin , data = ll.all.data[ll.all.data$donations > 0, ]), type = "hc2")
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summaryR.lm(lm(log(donations) ~ elected*votemargin , data = ll.all.data[ll.all.data$donations > 0, ]), type = "hc2")
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summaryR.lm(lm(log((pwcontracts.dnit.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.all.pw.data[ll.all.pw.data$pw.donations > 0, ]), type = "hc2")
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.all.pw.data[ll.all.pw.data$pw.donations > 0, ]), type = "hc2")
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.all.pw.data[ll.all.pw.data$pw.donations > 0, ]), type = "hc2")
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summaryR.lm(lm(log((pwcontracts.dnit.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.coal.pw.data[ll.coal.pw.data$pw.donations > 0, ]), type = "hc2")
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.coal.pw.data[ll.coal.pw.data$pw.donations > 0, ]), type = "hc2")
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.coal.pw.data[ll.coal.pw.data$pw.donations > 0, ]), type = "hc2")
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summaryR.lm(lm(log((pwcontracts.dnit.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.pt.pw.data[ll.pt.pw.data$pw.donations > 0, ]), type = "hc2")
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.pt.pw.data[ll.pt.pw.data$pw.donations > 0, ]), type = "hc2")
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.pt.pw.data[ll.pt.pw.data$pw.donations > 0, ]), type = "hc2")
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

##All candidates
ply.all <- summaryR.lm(lm(as.formula(paste("log((contracts.dnit.0810 + 1)/donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))   , data = ply.all.data[ply.all.data$donations > 0, ]))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summaryR.lm(lm(as.formula(paste("log(donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data[ply.all.data$donations > 0, ]), type = "hc2")
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summaryR.lm(lm(as.formula(paste("log((donations)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data[ply.all.data$donations > 0, ]), type = "hc2")
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data[ply.all.data$donations > 0, ])

##Public works
ply.all.pw <- summaryR.lm(lm(as.formula(paste("log((pwcontracts.dnit.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data[ply.all.pw.data$pw.donations > 0, ]), type = "hc2")
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data[ply.all.pw.data$pw.donations > 0, ]), type = "hc2")
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data[ply.all.pw.data$pw.donations > 0, ]), type = "hc2")
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data[ply.all.pw.data$pw.donations > 0, ])

##Coalition, public works
ply.coal.pw <- summaryR.lm(lm(as.formula(paste("log((pwcontracts.dnit.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data[ply.coal.pw.data$pw.donations > 0, ]), type = "hc2")
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data[ply.coal.pw.data$pw.donations > 0, ]), type = "hc2")
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data[ply.coal.pw.data$pw.donations > 0, ]), type = "hc2")
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summaryR.lm(lm(as.formula(paste("log((pwcontracts.dnit.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.data[ply.pt.pw.data$pw.donations > 0, ]))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data[ply.pt.pw.data$pw.donations > 0, ]), type = "hc2")
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data[ply.pt.pw.data$pw.donations > 0, ]), type = "hc2")
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data[ply.pt.pw.data$pw.donations > 0, ])


dnit.results.table <- data.frame(cbind(
  round(c(lo.all$est, lo.all.pw$est, lo.coal.pw$est, lo.pt.pw$est, ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(lo.all$se, lo.all.pw$se, lo.coal.pw$se, lo.pt.pw$se, ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c(lo.all$est.unlogged, lo.all.pw$est.unlogged, lo.coal.pw$est.unlogged, lo.pt.pw$est.unlogged, ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c(lo.all$donations, lo.all.pw$donations, lo.coal.pw$donations, lo.pt.pw$donations, ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(lo.all$N, lo.all.pw$N, lo.coal.pw$N, lo.pt.pw$N, ply.all$N, ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(dnit.results.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) issued by DNIT that are received by a candidate's corporate donors, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity.  The loess specification uses a bandwidth of ", prettyNum(lo.bw, big.mark = ",", scientific = FALSE), " votes and a span of ", span, ". The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " votes, respectively.  Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

#Note: The following command creates a latex table that can only be compiled when using the "ctable" latex package. 
#Note: The results in this latex table correspond to the results in the right half of Table 1 
dnit.results.table.latex <- latex(dnit.results.table, cdec = c(2, 2, 0, 0, 0), file = "table1_dnit_contracts.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Contracts from the National Department of Transportation Infrastructure (DNIT).", insert.bottom = bottom.note, rgroup = c("Loess Estimator", "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")

###########
#Appendix
##########

#############
### McCrary Density Test
#############

mccrary.all.raw <- with(lo.all.data, mccrary.test(force.var = votemargin))
mccrary.pw.raw <- with(lo.all.pw.data, mccrary.test(force.var = votemargin))
mccrary.pw.pt.raw <- with(lo.pt.pw.data, mccrary.test(force.var = votemargin))
mccrary.pw.coal.raw <- with(lo.coal.pw.data, mccrary.test(force.var = votemargin))

depfed.mccrary.table.raw <- cbind(
  "All" = c(unlist(mccrary.all.raw), nrow(lo.all.data)),
  "Pub. works" = c(unlist(mccrary.pw.raw), nrow(lo.all.pw.data)),
  "Pub. works, coalition" = c(unlist(mccrary.pw.coal.raw), nrow(lo.coal.pw.data)),
  "Pub. works, PT" = c(unlist(mccrary.pw.pt.raw), nrow(lo.pt.pw.data)) 
)

depfed.mccrary.table.raw.latex <- latex(depfed.mccrary.table.raw, rdec = c(2, 2, 0), col.just = rep("c", 4), rowname = c("Wald Stat." , "SE", "N"), rowlabel = "", caption = "McCrary Test of Continuity of the Forcing Variable: Federal Deputies", ctable = TRUE, file = "appendix_table1.tex", where = "htp")

########
##Figure 1: Histogram of Forcing Variable
########
#Histogram of Density of the Forcing variable
pdf(file = "appendix_figure1.pdf", width = 6, height = 6)
with(lo.all.data,
     hist(x = votemargin,
          breaks = seq(-40000, 40000, 2000),
          freq = TRUE,
          #          labels = TRUE,
          right = FALSE,
          xlim = c(-40000, 40000),
          ylim = c(0, 35),
          col = "grey",
          main = NULL,
          xlab = "Raw Vote Margin",
          ylab = "Frequency Count in 2000 Vote Bins",
          las = 1,
          #          cex.lab = 1.2,
          #          cex.main = 1.3
     )
)
abline(v = 0, lwd = 2, lty=2)
dev.off()

########
##Figure 2: Comparison of Forcing Variables
########
# Calculate inflation factor and inflated vote margin

depfed_data$infl.fact<-(depfed_data$votes/(depfed_data$votes-depfed_data$votemargin))
depfed_data$infl.fact[depfed_data$elected==0]<-depfed_data$infl.fact[depfed_data$elected==0]^-1 
depfed_data$infl.vote.margin<-depfed_data$votemargin*depfed_data$infl.fact

depfed<-unique(depfed_data[,c('uf','depfed.id','votemargin','margin.nomvote','margin.coalvote','infl.vote.margin')])

# Determine regions, population
raw<-readLines('http://www.guiadoturista.net/turismo/sobre-o-brasil/estados/')
uf<-gsub('.*</strong> ([A-Z]{2}).*','\\1',raw[grep('UF:',raw)])
region<-gsub('.*</strong> (.*)<.*','\\1',raw[grep('Região:',raw)])
region<-gsub(' *$','',region)
pop<-gsub('.*</strong> (.*)<.*','\\1',raw[grep('População:',raw)])
pop<-gsub(' hab.','',pop)
pop<-as.numeric(gsub('\\.','',pop))
pop.cat<-1*(pop<=quantile(pop,.4))+
  2*(pop>quantile(pop,.4)&pop<=quantile(pop,.6))+
  3*(pop>quantile(pop,.6)&pop<=quantile(pop,.8))+
  4*(pop>quantile(pop,.8))
pop.cat<-factor(pop.cat,labels=c('tiny','small','medium','large'))
regions<-data.frame(uf,region,pop,pop.cat)
depfed<-merge(depfed,regions)

abs.votemargin<-sort(unique(abs(depfed$votemargin)))
share.votemargin<-sapply(abs.votemargin,function(x){sum(abs(depfed$votemargin)<x)/length(depfed$votemargin)})
share.votemargin<-trunc(share.votemargin*100)/100
vals.votemargin<-abs.votemargin[match(10:90/100,share.votemargin)]

abs.coalmargin<-sort(unique(abs(depfed$margin.coalvote)))
share.coalmargin<-sapply(abs.coalmargin,function(x){sum(abs(depfed$margin.coalvote)<x)/length(depfed$margin.coalvote)})
share.coalmargin<-trunc(share.coalmargin*100)/100
vals.coalmargin<-abs.coalmargin[match(10:90/100,share.coalmargin)]

abs.nommargin<-sort(unique(abs(depfed$margin.nomvote)))
share.nommargin<-sapply(abs.nommargin,function(x){sum(abs(depfed$margin.nomvote)<x)/length(depfed$margin.nomvote)})
share.nommargin<-trunc(share.nommargin*100)/100
vals.nommargin<-abs.nommargin[match(10:90/100,share.nommargin)]

abs.inflmargin<-sort(unique(abs(depfed$infl.vote.margin)))
share.inflmargin<-sapply(abs.inflmargin,function(x){sum(abs(depfed$infl.vote.margin)<x)/length(depfed$infl.vote.margin)})
share.inflmargin<-trunc(share.inflmargin*100)/100
vals.inflmargin<-abs.inflmargin[match(10:90/100,share.inflmargin)]

# Calculate chi-squared statistics

chisq.votemargin<-sapply(vals.votemargin,function(x){chisq.test(depfed$pop.cat,abs(depfed$votemargin)<=x)$statistic})
chisq.coalmargin<-sapply(vals.coalmargin,function(x){chisq.test(depfed$pop.cat,abs(depfed$margin.coalvote)<=x)$statistic})
chisq.nommargin<-sapply(vals.nommargin,function(x){chisq.test(depfed$pop.cat,abs(depfed$margin.nomvote)<=x)$statistic})
chisq.inflmargin<-sapply(vals.inflmargin,function(x){chisq.test(depfed$pop.cat,abs(depfed$infl.vote.margin)<=x)$statistic})

# Calculate t-statistics

t.votemargin<-sapply(vals.votemargin,function(x){t.test(log(depfed$pop[abs(depfed$votemargin)<=x]),log(depfed$pop))$statistic})
t.coalmargin<-sapply(vals.coalmargin,function(x){t.test(log(depfed$pop[abs(depfed$margin.coalvote)<=x]),log(depfed$pop))$statistic})
t.nommargin<-sapply(vals.nommargin,function(x){t.test(log(depfed$pop[abs(depfed$margin.nomvote)<=x]),log(depfed$pop))$statistic})
t.inflmargin<-sapply(vals.inflmargin,function(x){t.test(log(depfed$pop[abs(depfed$infl.vote.margin)<=x]),log(depfed$pop))$statistic})


pdf("appendix_figure2.pdf", height = 6, width  = 6)
plot(10:90/100,abs(t.votemargin),col=1,type='l',lwd=2,lty=1,ylim=c(-2,18),xlab='Share of sample',ylab='|t|')
lines(10:90/100, abs(t.nommargin),col=3,type='l',lwd=2,lty=4)
lines(10:90/100, abs(t.inflmargin),col=2,type='l',lwd=2,lty=2)
#lines(10:90/100, abs(t.coalmargin),col=4,type='l',lwd=2,lty=3)
legend(x='bottomleft',legend=c('Standardized vote margin','Raw vote margin','Inflated vote margin'),text.col=c(3,1,2),lty=c(4,1,2),col=c(3,1,2))
#legend(x='bottomleft',legend=c('Raw vote margin','Vote margin/nominal votes','Inflated vote margin','Vote margin/coalition votes'),text.col=c(2,3,1,4),lty=c(2,4,1,3),col=c(2,3,1,4))
dev.off()

#########
##Figure 3: Balance Statistics - Standardized Differences
#########
pdf(file = "appendix_figure3.pdf", height = 6, width = 10)
ggplot(std.diff.table, aes(x = std.diff, y = Variable, shape = Sample, color = Sample)) + geom_point() + geom_vline(xintercept = 0, lty = 2, size = .2) + facet_grid(.~Estimator) + theme_bw() + scale_x_continuous("Standardized Difference") + scale_color_brewer(palette = "Set1") + opts(axis.title.x = theme_text(vjust = -0.3), title = "Balance Statistics for Federal Deputies")
dev.off()


####
##Figure 4: Balance Statistics: Differene-in-Means
#Check balance using difference-in-means

plot.bal.var <- c("incumbent", "contracts.0406", "pw.con.0406", "donations", "donor.firms", "pw.donor.firms", "pw.donations") 



window.size <- 4000
windows <- seq(0, 40000, by = 100)
min.pvals.all <- c()
min.pvals.pw <- c()
min.pvals.coal <- c()
min.pvals.pt <- c()
for(i in 1:length(windows)){
  win.all <- depfed.balance[(depfed.balance$votemargin >= windows[i] & depfed.balance$votemargin < (windows[i] + window.size)) | (depfed.balance$votemargin <= -1 * windows[i] & depfed.balance$votemargin > (-1 * windows[i] - window.size)), ]
  win.pw <- depfed.balance[(depfed.balance$votemargin >= windows[i] & depfed.balance$votemargin < (windows[i] + window.size)) | (depfed.balance$votemargin <= -1 * windows[i] & depfed.balance$votemargin > (-1 * windows[i] - window.size)) & depfed.balance$pw.donations > 0 , ]
  win.coal <- depfed.balance[(depfed.balance$votemargin >= windows[i] & depfed.balance$votemargin < (windows[i] + window.size)) | (depfed.balance$votemargin <= -1 * windows[i] & depfed.balance$votemargin > (-1 * windows[i] - window.size)) & depfed.balance$pw.donations > 0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA') , ]
  win.pt <- depfed.balance[(depfed.balance$votemargin >= windows[i] & depfed.balance$votemargin < (windows[i] + window.size)) | (depfed.balance$votemargin <= -1 * windows[i] & depfed.balance$votemargin > (-1 * windows[i] - window.size)) & depfed.balance$pw.donations > 0 & depfed.balance$party == "PT" , ]   
  p.vals.all <- c()
  p.vals.pw <- c()
  p.vals.coal <- c()
  p.vals.pt <- c()
  for(j in 1:length(plot.bal.var)){
    p.vals.all <- c(p.vals.all, t.test( win.all[, plot.bal.var[j]] ~ win.all$elected)$p.value)
    p.vals.pw <- c(p.vals.pw, t.test( win.pw[, plot.bal.var[j]] ~ win.pw$elected)$p.value)
    p.vals.coal <- c(p.vals.coal, t.test( win.coal[, plot.bal.var[j]] ~ win.coal$elected)$p.value)
    p.vals.pt<- c(p.vals.pt, tryCatch(t.test( win.pt[, plot.bal.var[j]] ~ win.pt$elected)$p.value, error = function(e) NA))   
  }
  min.pvals.all <- c(min.pvals.all, min(p.vals.all))
  min.pvals.pw <- c(min.pvals.pw, min(p.vals.pw))
  min.pvals.coal <- c(min.pvals.coal, min(p.vals.coal))  
  min.pvals.pt <- c(min.pvals.pt, min(p.vals.pt))
}

ttest.plot.data <- rbind(data.frame(votemargin = windows, min.pval = min.pvals.all, Sample = "All"),
                         data.frame(votemargin = windows, min.pval = min.pvals.pw, Sample = "Public Works"),
                         data.frame(votemargin = windows, min.pval = min.pvals.coal, Sample = "Pub. Works, Coalition"),
                         data.frame(votemargin = windows, min.pval = min.pvals.pt, Sample = "Pub. Works, PT")
)

pdf(file = "appendix_figure4.pdf", height = 6, width = 10)
ggplot(ttest.plot.data, aes(x = votemargin, y = min.pval)) + geom_point() + facet_wrap(~ Sample, ncol = 2, scales = "free_y") + geom_smooth(se = FALSE, size = 1.5, span = .2) + theme_bw() + xlab("Absolute Value of Vote Margin") + ylab("Minimum p value")
dev.off()

#####
##Table 2: The Effect (for Compliers) of Electoral Victory on Future Federal Government Contracts
####

ply.all.data$served.legis <- ply.all.data$elected
ply.all.data$served.legis[ply.all.data$licenca.days > 669 ] <- 0
ply.all.data$served.legis[ply.all.data$suplencia.days > 669 ] <- 1

ply.all.pw.data$served.legis <- ply.all.pw.data$elected
ply.all.pw.data$served.legis[ply.all.pw.data$licenca.days > 669 ] <- 0
ply.all.pw.data$served.legis[ply.all.pw.data$suplencia.days > 669 ] <- 1

ply.coal.pw.data$served.legis <- ply.coal.pw.data$elected
ply.coal.pw.data$served.legis[ply.coal.pw.data$licenca.days > 669 ] <- 0
ply.coal.pw.data$served.legis[ply.coal.pw.data$suplencia.days > 669 ] <- 1

ply.pt.pw.data$served.legis <- ply.pt.pw.data$elected
ply.pt.pw.data$served.legis[ply.pt.pw.data$licenca.days > 669 ] <- 0
ply.pt.pw.data$served.legis[ply.pt.pw.data$suplencia.days > 669 ] <- 1

ll.all.data$served.legis <- ll.all.data$elected
ll.all.data$served.legis[ll.all.data$licenca.days > 669 ] <- 0
ll.all.data$served.legis[ll.all.data$suplencia.days > 669 ] <- 1 

ll.all.pw.data$served.legis <- ll.all.pw.data$elected
ll.all.pw.data$served.legis[ll.all.pw.data$licenca.days > 669 ] <- 0
ll.all.pw.data$served.legis[ll.all.pw.data$suplencia.days > 669 ] <- 1 

ll.coal.pw.data$served.legis <- ll.coal.pw.data$elected
ll.coal.pw.data$served.legis[ll.coal.pw.data$licenca.days > 669 ] <- 0
ll.coal.pw.data$served.legis[ll.coal.pw.data$suplencia.days > 669 ] <- 1 

ll.pt.pw.data$served.legis <- ll.pt.pw.data$elected
ll.pt.pw.data$served.legis[ll.pt.pw.data$licenca.days > 669 ] <- 0
ll.pt.pw.data$served.legis[ll.pt.pw.data$suplencia.days > 669 ] <- 1 

ivll.all <- summary(ivreg(log((contracts.0810 + 1) / donor.firms) ~ served.legis*votemargin | elected*votemargin , data = ll.all.data))
ivll.all$est.unlogged <-reais.format(exp(coef(ivll.all)[1,1] + coef(ivll.all)[2,1]) - exp(coef(ivll.all)[1,1]))
ivll.all$donors <- summary(ivreg(log(donor.firms) ~ served.legis | elected , data = ll.all.data))
ivll.all$donors <- mean(exp(coef(ivll.all$donors)[1,1] + coef(ivll.all$donors)[2,1]), exp(coef(ivll.all$donors)[1,1]))
ivll.all$donations <- summary(ivreg(log(donations) ~ served.legis | elected , data = ll.all.data))
ivll.all$donations <- reais.format(mean(exp(coef(ivll.all$donations)[1,1] + coef(ivll.all$donations)[2,1]), exp(coef(ivll.all$donations)[1,1])))
ivll.all$N <- nrow(ll.all.data)


ivll.all.pw <- summary(ivreg(log((pw.con.0810 + 1)/pw.donor.firms) ~ served.legis*votemargin | elected*votemargin , data = ll.all.pw.data))
ivll.all.pw$est.unlogged <-reais.format(exp(coef(ivll.all.pw)[1,1] + coef(ivll.all.pw)[2,1]) - exp(coef(ivll.all.pw)[1,1]))
ivll.all.pw$donors <- summary(ivreg(log(pw.donor.firms) ~ served.legis | elected , data = ll.all.pw.data))
ivll.all.pw$donors <- mean(exp(coef(ivll.all.pw$donors)[1,1] + coef(ivll.all.pw$donors)[2,1]), exp(coef(ivll.all.pw$donors)[1,1]))
ivll.all.pw$donations <- summary(ivreg(log(pw.donations) ~ served.legis | elected , data = ll.all.pw.data))
ivll.all.pw$donations <- reais.format(mean(exp(coef(ivll.all.pw$donations)[1,1] + coef(ivll.all.pw$donations)[2,1]), exp(coef(ivll.all.pw$donations)[1,1])))
ivll.all.pw$N <- nrow(ll.all.pw.data)


ivll.coal.pw <- summary(ivreg(log((pw.con.0810 + 1)/pw.donor.firms) ~ served.legis*votemargin | elected*votemargin , data = ll.coal.pw.data))
ivll.coal.pw$est.unlogged <-reais.format(exp(coef(ivll.coal.pw)[1,1] + coef(ivll.coal.pw)[2,1]) - exp(coef(ivll.coal.pw)[1,1]))
ivll.coal.pw$donors <- summary(ivreg(log(pw.donor.firms) ~ served.legis | elected , data = ll.coal.pw.data))
ivll.coal.pw$donors <- mean(exp(coef(ivll.coal.pw$donors)[1,1] + coef(ivll.coal.pw$donors)[2,1]), exp(coef(ivll.coal.pw$donors)[1,1]))
ivll.coal.pw$donations <- summary(ivreg(log(pw.donations) ~ served.legis | elected , data = ll.coal.pw.data))
ivll.coal.pw$donations <- reais.format(mean(exp(coef(ivll.coal.pw$donations)[1,1] + coef(ivll.coal.pw$donations)[2,1]), exp(coef(ivll.coal.pw$donations)[1,1])))
ivll.coal.pw$N <- nrow(ll.coal.pw.data)

ivll.pt.pw <- summary(ivreg(log((pw.con.0810 + 1)/pw.donor.firms) ~ served.legis*votemargin | elected*votemargin , data = ll.pt.pw.data))
ivll.pt.pw$est.unlogged <-reais.format(exp(coef(ivll.pt.pw)[1,1] + coef(ivll.pt.pw)[2,1]) - exp(coef(ivll.pt.pw)[1,1]))
ivll.pt.pw$donors <- summary(ivreg(log(pw.donor.firms) ~ served.legis | elected , data = ll.pt.pw.data))
ivll.pt.pw$donors <- mean(exp(coef(ivll.pt.pw$donors)[1,1] + coef(ivll.pt.pw$donors)[2,1]), exp(coef(ivll.pt.pw$donors)[1,1]))
ivll.pt.pw$donations <- summary(ivreg(log(pw.donations) ~ served.legis | elected , data = ll.pt.pw.data))
ivll.pt.pw$donations <- reais.format(mean(exp(coef(ivll.pt.pw$donations)[1,1] + coef(ivll.pt.pw$donations)[2,1]), exp(coef(ivll.pt.pw$donations)[1,1])))
ivll.pt.pw$N <- nrow(ll.pt.pw.data)



ivply.all <- (ivreg(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))), data = ply.all.data))
ivply.all$est.unlogged <-reais.format(exp(coef(ivply.all)[1] + coef(ivply.all)[2]) - exp(coef(ivply.all)[1]))
ivply.all$donors <- (ivreg(as.formula(paste("log(donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.all.data))
ivply.all$donors <- mean(exp(coef(ivply.all$donors)[1] + coef(ivply.all$donors)[2]), exp(coef(ivply.all$donors)[1]))
ivply.all$donations <- (ivreg(as.formula(paste("log(donations) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.all.data))
ivply.all$donations <- reais.format(mean(exp(coef(ivply.all$donations)[1] + coef(ivply.all$donations)[2]), exp(coef(ivply.all$donations)[1])))
ivply.all$N <- nrow(ply.all.data)


ivply.all.pw <- (ivreg(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.all.pw.data))
ivply.all.pw$est.unlogged <-reais.format(exp(coef(ivply.all.pw)[1] + coef(ivply.all.pw)[2]) - exp(coef(ivply.all.pw)[1]))
ivply.all.pw$donors <- (ivreg(as.formula(paste("log(pw.donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.all.pw.data))
ivply.all.pw$donors <- mean(exp(coef(ivply.all.pw$donors)[1] + coef(ivply.all.pw$donors)[2]), exp(coef(ivply.all.pw$donors)[1]))
ivply.all.pw$donations <- (ivreg(as.formula(paste("log(pw.donations) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))), data = ply.all.pw.data))
ivply.all.pw$donations <- reais.format(mean(exp(coef(ivply.all.pw$donations)[1] + coef(ivply.all.pw$donations)[2]), exp(coef(ivply.all.pw$donations)[1])))
ivply.all.pw$N <- nrow(ply.all.pw.data)


ivply.coal.pw <- (ivreg(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.coal.pw.data))
ivply.coal.pw$est.unlogged <-reais.format(exp(coef(ivply.coal.pw)[1] + coef(ivply.coal.pw)[2]) - exp(coef(ivply.coal.pw)[1]))
ivply.coal.pw$donors <- (ivreg(as.formula(paste("log(pw.donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.coal.pw.data))
ivply.coal.pw$donors <- mean(exp(coef(ivply.coal.pw$donors)[1] + coef(ivply.coal.pw$donors)[2]), exp(coef(ivply.coal.pw$donors)[1]))
ivply.coal.pw$donations <- (ivreg(as.formula(paste("log(pw.donations) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.coal.pw.data))
ivply.coal.pw$donations <- reais.format(mean(exp(coef(ivply.coal.pw$donations)[1] + coef(ivply.coal.pw$donations)[2]), exp(coef(ivply.coal.pw$donations)[1])))
ivply.coal.pw$N <- nrow(ply.coal.pw.data)

ivply.pt.pw <- (ivreg(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.pt.pw.data))
ivply.pt.pw$est.unlogged <-reais.format(exp(coef(ivply.pt.pw)[1] + coef(ivply.pt.pw)[2]) - exp(coef(ivply.pt.pw)[1]))
ivply.pt.pw$donors <- (ivreg(as.formula(paste("log(pw.donor.firms) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))), data = ply.pt.pw.data))
ivply.pt.pw$donors <- mean(exp(coef(ivply.pt.pw$donors)[1] + coef(ivply.pt.pw$donors)[2]), exp(coef(ivply.pt.pw$donors)[1]))
ivply.pt.pw$donations <- (ivreg(as.formula(paste("log(pw.donations) ~ served.legis * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * served.legis", sep ="", collapse = " + "), paste("| elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), sep = ""))) , data = ply.pt.pw.data))
ivply.pt.pw$donations <- reais.format(mean(exp(coef(ivply.pt.pw$donations)[1] + coef(ivply.pt.pw$donations)[2]), exp(coef(ivply.pt.pw$donations)[1])))
ivply.pt.pw$N <- nrow(ply.pt.pw.data)

iv.results.table <- data.frame(cbind(
  round(c(coef(ivply.all)[2], coef(ivply.all.pw)[2] ,coef(ivply.coal.pw)[2], coef(ivply.pt.pw)[2], coef(ivll.all)[2,1], coef(ivll.all.pw)[2,1] ,coef(ivll.coal.pw)[2,1], coef(ivll.pt.pw)[2,1]), 2),
  round(c(sqrt(vcov(ivply.all))[2,2], sqrt(vcov(ivply.all.pw))[2,2] , sqrt(vcov(ivply.coal.pw)[2,2]), sqrt(vcov(ivply.pt.pw))[2,2], coef(ivll.all)[2,2], coef(ivll.all.pw)[2,2] ,coef(ivll.coal.pw)[2,2], coef(ivll.pt.pw)[2,2]), 2),
  #        c(ivdm.all$est.unlogged, ivdm.all.pw$est.unlogged, ivdm.coal.pw$est.unlogged, ivdm.pt.pw$est.unlogged, ivll.all$est.unlogged, ivll.all.pw$est.unlogged, ivll.coal.pw$est.unlogged, ivll.pt.pw$est.unlogged),
  #                                     c(ivdm.all$donations, ivdm.all.pw$donations, ivdm.coal.pw$donations, ivdm.pt.pw$donations, ivll.all$donations, ivll.all.pw$donations, ivll.coal.pw$donations, ivll.pt.pw$donations),
  c(ivply.all$N, ivply.all.pw$N, ivply.coal.pw$N, ivply.pt.pw$N, ivll.all$N, ivll.all.pw$N, ivll.coal.pw$N, ivll.pt.pw$N)
))


names(iv.results.table) <- c("Complier Effect", "SE" , "N"  )
bottom.note <- paste("These specifications instrument serving in the legislature with whether or not the candidate won the election. Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010.")

iv.results.table.latex <- latex(iv.results.table, cdec = c(2, 2, 0), file = "appendix_table2.tex", col.just = rep("c", 3), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT"), rowlabel = "Sample", caption = "The Effect (for Compliers) of Electoral Victory on Future Federal Government Contracts", insert.bottom = bottom.note, rgroup = c( "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4), booktabs = FALSE, ctable = TRUE, where = "htp")

###
##Table 3: Table 3: The Effect of Electoral Victory on Future Federal Government Contracts, Weighting by Log Population
###

##All candidates
ll.all <- summary(lm(log((contracts.0810 + 1)/donor.firms) ~ elected*votemargin, data = ll.all.data, weights = log(voters)))
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summary(lm(log(donor.firms) ~ elected*votemargin , data = ll.all.data), weights = log(voters))
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summary(lm(log(donations) ~ elected*votemargin , data = ll.all.data), weights = log(voters))
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summary(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.all.pw.data, weights = log(voters)))
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summary(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.all.pw.data, weights = log(voters)))
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summary(lm(log(pw.donations) ~ elected*votemargin , data = ll.all.pw.data, weights = log(voters)))
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summary(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.coal.pw.data, weights = log(voters)))
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summary(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.coal.pw.data, weights = log(voters)))
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summary(lm(log(pw.donations) ~ elected*votemargin , data = ll.coal.pw.data, weights = log(voters)))
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summary(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin, data = ll.pt.pw.data, weights = log(voters)))
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summary(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.pt.pw.data, weights = log(voters)))
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summary(lm(log(pw.donations) ~ elected*votemargin , data = ll.pt.pw.data, weights = log(voters)))
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

##All candidates
ply.all <- summary(lm(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))   , data = ply.all.data, weights = log(voters)))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summary(lm(as.formula(paste("log(donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data, weights = log(voters)))
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summary(lm(as.formula(paste("log((donations)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data, weights = log(voters)))
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data)

##Public works
ply.all.pw <- summary(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data, weights = log(voters)))
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summary(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data, weights = log(voters)))
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summary(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data, weights = log(voters)))
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw <- summary(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data, weights = log(voters)))
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summary(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data, weights = log(voters)))
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summary(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data, weights = log(voters)))
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summary(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.data, weights = log(voters)))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summary(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data, weights = log(voters)))
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summary(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data, weights = log(voters)))
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data)

##Gather all results into one table
statepopwts.results.table <- data.frame(cbind(
  round(c(ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c( ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c( ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(ply.all$N, ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(statepopwts.results.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity. The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " votes, respectively. Observations are weighted by the log of state population.", sep = "")

statepopwts.results.table.latex <- latex(statepopwts.results.table, cdec = c(2, 2, 0, 0, 0), file = "appendix_table3.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts, Weighting by Log Population", insert.bottom = bottom.note, rgroup = c("Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")

#####
#Figure 5: Balance Statistics using Inflated Vote Margin
#####

depfed_data$incumbent <- depfed.balance$incumbent
##Loess Data, Estimation Samples
lo.bw <- 100000
lo.all.data <- depfed_data[abs(depfed_data$infl.vote.margin)<lo.bw & depfed_data$donations>0,]
lo.all.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<lo.bw & depfed_data$pw.donations>0,]
lo.coal.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Loess Data, Balance Samples
lo.all.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<lo.bw & depfed.balance$donations>0,]
lo.all.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<lo.bw & depfed.balance$pw.donations>0,]
lo.coal.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<lo.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<lo.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]


###Difference in Means Bandwidth
dm.bw <- 10000
##Difference in Means Data, Estimation Samples
dm.all.data <- depfed_data[abs(depfed_data$infl.vote.margin) < dm.bw & depfed_data$donations > 0,]
dm.all.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<dm.bw & depfed_data$pw.donations>0,]
dm.coal.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<dm.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
dm.pt.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<dm.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Difference in Means Data, Balance Samples
dm.all.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin) < dm.bw & depfed.balance$donations > 0,]
dm.all.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<dm.bw & depfed.balance$pw.donations>0,]
dm.coal.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<dm.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
dm.pt.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<dm.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]

###Local Linear Bandwidth
ll.bw <- 30000
##Local Linear Data, Estimation Samples
ll.all.data <- depfed_data[abs(depfed_data$infl.vote.margin) < ll.bw & depfed_data$donations > 0,]
ll.all.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<ll.bw & depfed_data$pw.donations>0,]
ll.coal.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Local Linear Data, Balance Samples
ll.all.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin) < ll.bw & depfed.balance$donations > 0,]
ll.all.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<ll.bw & depfed.balance$pw.donations>0,]
ll.coal.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<ll.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin)<ll.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]



##Polynomial Data, Estimation Samples
poly.order <- 3
ply.bw <- 150000
ply.all.data <- depfed_data[abs(depfed_data$infl.vote.margin) < ply.bw & depfed_data$donations > 0,]
ply.all.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin) < ply.bw & depfed_data$pw.donations>0,]
ply.coal.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.data <- depfed_data[abs(depfed_data$infl.vote.margin) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Polynomial Data, Balance Samples
ply.all.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin) < ply.bw & depfed.balance$donations > 0,]
ply.all.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin) < ply.bw & depfed.balance$pw.donations>0,]
ply.coal.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin) < ply.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.baldata <- depfed.balance[abs(depfed.balance$infl.vote.margin) < ply.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]

bal.var <- c("coalvotes", "incumbent", "contracts.0406", "pw.con.0406", "donations", "pw.donations", "donor.firms", "pw.donor.firms", "year.opened", "commerce", "manufacture", "financial", "cand.uf.sp", "cand.uf.mg", "cand.uf.rs", "cand.uf.ba", "cand.uf.rj", "party.psdb", "party.pfl", "party.pt", "party.pmdb", "superior.edu", "occ.pol", "yob", "individ.donations", "occ.business", "coalvotes", "individual.donors", "coalseats", "agriculture", "numb.company.recipients", "total.company.donations", "totalDonations.winners.firm", "winners.donated.to")

lo.bal <- list()
lo.bal$all <- list()
lo.bal$all.pw <- list()
lo.bal$coal.pw <- list()
lo.bal$pt.pw <- list()

dm.bal <- list()
dm.bal$all <- list()
dm.bal$all.pw <- list()
dm.bal$coal.pw <- list()
dm.bal$pt.pw <- list()


ll.bal <- list()
ll.bal$all <- list()
ll.bal$all.pw <- list()
ll.bal$coal.pw <- list()
ll.bal$pt.pw <- list()
length(ll.bal$pt.pw) <- length(bal.var)

ply.bal <- list()
ply.bal$all <- list()
ply.bal$all.pw <- list()
ply.bal$coal.pw <- list()
ply.bal$pt.pw <- list()
length(ply.bal$pt.pw) <- length(bal.var)

for(i in 1:length(bal.var)){
  print(paste("Checking Balance on", bal.var[i]))
  lo.bal$all[[i]] <- with(lo.all.baldata, lo.ate(y = lo.all.baldata[ , bal.var[i]], treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
  lo.bal$all[[i]]$sd <- (sd(lo.all.baldata[lo.all.baldata$elected == 1 , bal.var[i]]) + sd(lo.all.baldata[lo.all.baldata$elected == 0 , bal.var[i]])) / 2
  names(lo.bal$all)[i] <- bal.var[i]
  
  lo.bal$all.pw[[i]] <- with(lo.all.pw.baldata, lo.ate(y = lo.all.pw.baldata[, bal.var[i]], treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
  lo.bal$all.pw[[i]]$sd <- (sd(lo.all.pw.baldata[lo.all.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.all.pw.baldata[lo.all.pw.baldata$elected == 0 , bal.var[i]])) / 2
  names(lo.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(lo.coal.pw.baldata[ , bal.var[i]])) == 1){
    lo.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(lo.coal.pw.baldata[ , bal.var[i]])) > 1){
    lo.bal$coal.pw[[i]] <- with(lo.coal.pw.baldata, lo.ate(y = lo.coal.pw.baldata[, bal.var[i]], treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
    lo.bal$coal.pw[[i]]$sd <- (sd(lo.coal.pw.baldata[lo.coal.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.coal.pw.baldata[lo.coal.pw.baldata$elected == 0 , bal.var[i]])) / 2  
  }
  names(lo.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(lo.pt.pw.baldata[ , bal.var[i]])) == 1){
    lo.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(lo.pt.pw.baldata[ , bal.var[i]])) > 1){
    lo.bal$pt.pw[[i]] <- with(lo.pt.pw.baldata, lo.ate(y = lo.pt.pw.baldata[, bal.var[i]], treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
    lo.bal$pt.pw[[i]]$sd <- (sd(lo.pt.pw.baldata[lo.pt.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.pt.pw.baldata[lo.pt.pw.baldata$elected == 0 , bal.var[i]])) / 2
  }
  names(lo.bal$pt.pw)[i] <- bal.var[i]
  
  dm.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.all.baldata), type = "hc2")
  dm.bal$all[[i]]$sd <- (sd(dm.all.baldata[dm.all.baldata$elected == 1, bal.var[i]]) + sd(dm.all.baldata[dm.all.baldata$elected == 0, bal.var[i]])) / 2
  names(dm.bal$all)[i] <- bal.var[i]
  
  dm.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.all.pw.baldata), type = "hc2")
  dm.bal$all.pw[[i]]$sd <- (sd(dm.all.pw.baldata[dm.all.pw.baldata$elected == 1, bal.var[i]]) + sd(dm.all.pw.baldata[dm.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(dm.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(dm.coal.pw.baldata[ , bal.var[i]])) == 1){
    dm.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(dm.coal.pw.baldata[ , bal.var[i]])) > 1){
    dm.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.coal.pw.baldata), type = "hc2")
    dm.bal$coal.pw[[i]]$sd <- (sd(dm.coal.pw.baldata[dm.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(dm.coal.pw.baldata[dm.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(dm.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(dm.pt.pw.baldata[ , bal.var[i]])) == 1){
    dm.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(dm.pt.pw.baldata[ , bal.var[i]])) > 1){ 
    dm.bal$pt.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.pt.pw.baldata), type = "hc2")
    dm.bal$pt.pw[[i]]$sd <- (sd(dm.pt.pw.baldata[dm.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(dm.pt.pw.baldata[dm.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(dm.bal$pt.pw)[i] <- bal.var[i]
  
  ll.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*infl.vote.margin")) , data = ll.all.baldata), type = "hc2")
  ll.bal$all[[i]]$sd <- (sd(ll.all.baldata[ll.all.baldata$elected == 1, bal.var[i]]) + sd(ll.all.baldata[ll.all.baldata$elected == 0, bal.var[i]])) / 2
  names(ll.bal$all)[i] <- bal.var[i]
  
  ll.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*infl.vote.margin")) , data = ll.all.pw.baldata), type = "hc2")
  ll.bal$all.pw[[i]]$sd <- (sd(ll.all.pw.baldata[ll.all.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.all.pw.baldata[ll.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(ll.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(ll.coal.pw.baldata[ , bal.var[i]])) == 1){
    ll.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(ll.coal.pw.baldata[ , bal.var[i]])) > 1){
    ll.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*infl.vote.margin")) , data = ll.coal.pw.baldata), type = "hc2")
    ll.bal$coal.pw[[i]]$sd <- (sd(ll.coal.pw.baldata[ll.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.coal.pw.baldata[ll.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(ll.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(ll.pt.pw.baldata[ , bal.var[i]])) == 1){
    ll.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(ll.pt.pw.baldata[ , bal.var[i]])) > 1){
    ll.bal$pt.pw[[i]] <- tryCatch(summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*infl.vote.margin")) , data = ll.pt.pw.baldata), type = "hc2"), error = function(e) NA)
    if(is.na(ll.bal$pt.pw[[i]][1]) == FALSE){
      ll.bal$pt.pw[[i]]$sd <- (sd(ll.pt.pw.baldata[ll.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.pt.pw.baldata[ll.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
    }
  }
  names(ll.bal$pt.pw)[i] <- bal.var[i]  
  ply.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.all.baldata), type = "hc2")
  ply.bal$all[[i]]$sd <- (sd(ply.all.baldata[ply.all.baldata$elected == 1, bal.var[i]]) + sd(ply.all.baldata[ply.all.baldata$elected == 0, bal.var[i]])) / 2
  names(ply.bal$all)[i] <- bal.var[i]
  
  ply.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.all.pw.baldata), type = "hc2")
  ply.bal$all.pw[[i]]$sd <- (sd(ply.all.pw.baldata[ply.all.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.all.pw.baldata[ply.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(ply.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(ply.coal.pw.baldata[ , bal.var[i]])) == 1){
    ply.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(ply.coal.pw.baldata[ , bal.var[i]])) > 1){
    ply.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.baldata), type = "hc2")
    ply.bal$coal.pw[[i]]$sd <- (sd(ply.coal.pw.baldata[ply.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.coal.pw.baldata[ply.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(ply.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(ply.pt.pw.baldata[ , bal.var[i]])) == 1){
    ply.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(ply.pt.pw.baldata[ , bal.var[i]])) > 1){
    ply.bal$pt.pw[[i]] <- tryCatch(summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.baldata), type = "hc2"), error = function(e) NA)
    if(is.na(ply.bal$pt.pw[[i]][1]) == FALSE){
      ply.bal$pt.pw[[i]]$sd <- (sd(ply.pt.pw.baldata[ply.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.pt.pw.baldata[ply.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
    }
  }
  names(ply.bal$pt.pw)[i] <- bal.var[i]
  
}

lo.bal <- lapply(lo.bal, function(x){x[is.na(x)] <- NULL; x})
ll.bal <- lapply(ll.bal, function(x){x[is.na(x)] <- NULL; x})
dm.bal <- lapply(dm.bal, function(x){x[is.na(x)] <- NULL; x})
ply.bal <- lapply(ply.bal, function(x){x[is.na(x)] <- NULL; x})
std.diff.table <- data.frame(Estimate = c(
  ldply(lo.bal, function(x) ldply(x, function(x) x$est))$V1,
  ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1,
  ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1),
                             SD = c(
                               ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$V1,
                               ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$V1,
                               ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$V1),
                             Variable = c(
                               ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$.id,
                               ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$.id,
                               ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$.id),  
                             Sample = c(rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(lo.bal, length)), 
                                        rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), 
                                            sapply(ply.bal, length)),
                                        rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(ll.bal, length))
                             ),
                             Estimator = c(
                               rep("Loess", sum(sapply(lo.bal, length))), 
                               rep("Polynomial", sum(sapply(ply.bal, length))), rep("Local Linear", sum(sapply(ll.bal, length))))
)
std.diff.table$std.diff <- std.diff.table$Estimate / std.diff.table$SD
std.diff.table$Variable <- reorder(std.diff.table$Variable, std.diff.table$std.diff, mean)

tstat.table <- data.frame(Estimate = c(
  ldply(lo.bal, function(x) ldply(x, function(x) x$est))$V1,
  ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1,
  ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1),
                          SE = c(
                            ldply(lo.bal, function(x) ldply(x, function(x) x$se))$V1,
                            ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,2]))$V1,
                            ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,2]))$V1),
                          Variable = c(
                            ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$.id,
                            ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$.id,
                            ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$.id),  
                          Sample = c(
                            rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(lo.bal, length)), 
                            rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(ply.bal, length)),
                            rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(ll.bal, length))
                          ),
                          Estimator = c(
                            rep("Loess", sum(sapply(lo.bal, length))),
                            rep("Polynomial", sum(sapply(ply.bal, length))), rep("Local Linear", sum(sapply(ll.bal, length))))
)
tstat.table$tstat <- abs(tstat.table$Estimate / tstat.table$SE)
tstat.table$Variable <- reorder(tstat.table$Variable, tstat.table$tstat, max)

std.diff.table$Variable <- recode(std.diff.table$Variable, c("'coalvotes' = 'Coalition Votes'; 'yob' = 'Birth Year'; 'comm.donations' = 'Party Donations'; 'incumbent' = 'Incumbent'; 'contracts.0406' = 'Contracts (\\'04-\\'06)'; 'pw.con.0406' = 'Pub. Works Contracts (\\'04-\\'06)'; 'donations' = 'Total Donations Received'; 'pw.donations' = 'Pub. Works Donations Received'; 'donor.firms' = 'No. Donor Firms'; 'pw.donor.firms' = 'Pct. Pub. Works Donors'; 'year.opened' = 'Mean Donor Year Founded'; 'commerce' = 'Pct. Commerce Donors'; 'manufacture' = 'Pct. Manufacturing Donors'; 'financial' = 'Pct. Financial Donors'; 'agriculture' = 'Pct. Agricultural Donors'; 'cand.uf.sp' = 'State - São Paulo'; 'cand.uf.mg' = 'State - Minas Gerais';  'cand.uf.rs' = 'State - Rio Grande do Sul'; 'superior.edu' = 'Higher Education'; 'occ.pol' = 'Occupation - Politician'; 'individ.donations' = 'Individual Donations'; 'numb.company.recipients' = 'Mean Donor No. Candidate Receipients'; 'party.pmdb' = 'Party - PMDB'; 'party.pfl' = 'Party - PFL'; 'total.company.donations' = 'Mean Donor Total Donations'; 'coalvotes' = 'Coalition Votes'; 'party.pt' = 'Party - PT'; 'party.psdb' = 'Party - PSDB'; 'occ.business' = 'Occupation - Business'; 'cand.uf.rj' = 'State - Rio de Janeiro'; 'cand.uf.ba' = 'State - Bahia'; 'coalseats' = 'Coalition Seats'; 'individual.donors' = 'No. Individual Donors'; 'totalDonations.winners.firm' = 'Mean Donor Donations to Winners'; 'winners.donated.to' = 'Mean Donor No. Winning Recipients'"))

tstat.table$Variable <- recode(tstat.table$Variable, c("'coalvotes' = 'Coalition Votes'; 'yob' = 'Birth Year'; 'comm.donations' = 'Party Donations'; 'incumbent' = 'Incumbent'; 'contracts.0406' = 'Contracts (\\'04-\\'06)'; 'pw.con.0406' = 'Pub. Works Contracts (\\'04-\\'06)'; 'donations' = 'Total Donations Received'; 'pw.donations' = 'Pub. Works Donations Received'; 'donor.firms' = 'Donor Firms'; 'pw.donor.firms' = 'Pct. Pub. Works Donors'; 'year.opened' = 'Mean Donor Year Founded'; 'commerce' = 'Pct. Commerce Donors'; 'manufacture' = 'Pct. Manufacturing Donors'; 'financial' = 'Pct. Financial Donors'; 'agriculture' = 'Pct. Agricultural Donors'; 'cand.uf.sp' = 'State - São Paulo'; 'cand.uf.mg' = 'State - Minas Gerais';  'cand.uf.rs' = 'State - Rio Grande do Sul'; 'superior.edu' = 'Higher Education'; 'occ.pol' = 'Occupation - Politician'; 'individ.donations' = 'Individual Donations'; 'numb.company.recipients' = 'Mean Donor Candidate Receipients'; 'party.pmdb' = 'Party - PMDB'; 'party.pfl' = 'Party - PFL'; 'total.company.donations' = 'Mean Donor Total Donations'; 'coalvotes' = 'Coalition Votes'; 'party.pt' = 'Party - PT'; 'party.psdb' = 'Party - PSDB'; 'occ.business' = 'Occupation - Business'; 'cand.uf.rj' = 'State - Rio de Janeiro'; 'cand.uf.ba' = 'State - Bahia'; 'coalseats' = 'Coalition Seats'; 'individual.donors' = 'Individual Donors'; 'totalDonations.winners.firm' = 'Mean Donor Donations to Winners'; 'winners.donated.to' = 'Mean Donor Winning Recipients'"))
levels(tstat.table$Sample) <- c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT")

pdf(file = "appendix_figure5.pdf", height = 6, width = 10)
ggplot(tstat.table, aes(x = tstat, y = Variable, shape = Sample, color = Sample)) + geom_point() + geom_vline(xintercept = 2, lty = 2, size = .2) + facet_grid(.~Estimator) + theme_bw() + scale_x_continuous("T Statistic") + scale_color_brewer(palette = "Set1") + opts(axis.title.x = theme_text(vjust = -0.3), title = "Balance Statistics for Federal Deputies")
dev.off()

########
##Table 4: The Effect of Electoral Victory on Future Federal Government Contracts Using Inflated Vote Margin
########

###Loess Estimator
##All Donation Recipients
lo.all <-  with(lo.all.data, lo.ate(y = log((contracts.0810 + 1)/donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.all$est.unlogged <- reais.format(exp(lo.all$tr.est) - exp(lo.all$con.est))
lo.all$num.donors <- with(lo.all.data, lo.ate(y = log(donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.all$num.donors <- mean(exp(lo.all$num.donors$tr.est), exp(lo.all$num.donors$con.est))
lo.all$donations <- with(lo.all.data , lo.ate(y = log(donations), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.all$donations <- reais.format(mean(exp(lo.all$donations$tr.est) , exp(lo.all$donations$con.est)) / lo.all$num.donors)
lo.all$N <- nrow(depfed_data[abs(depfed_data$infl.vote.margin) < lo.bw & depfed_data$donations>0,]) 

##Public Works, all
lo.all.pw <- with(lo.all.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$est.unlogged <- reais.format(exp(lo.all.pw$tr.est) - exp(lo.all.pw$con.est))
lo.all.pw$num.donors <- with(lo.all.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$num.donors <- mean(exp(lo.all.pw$num.donors$tr.est), exp(lo.all.pw$num.donors$con.est))
lo.all.pw$donations <- with(lo.all.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$donations <- reais.format(mean(exp(lo.all.pw$donations$tr.est) , exp(lo.all.pw$donations$con.est)) / lo.all.pw$num.donors)
lo.all.pw$N <- nrow(lo.all.pw.data)

##Public works, coalition
lo.coal.pw <- with(lo.coal.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$est.unlogged <- reais.format(exp(lo.coal.pw$tr.est) - exp(lo.coal.pw$con.est))
lo.coal.pw$num.donors <- with(lo.coal.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$num.donors <- mean(exp(lo.coal.pw$num.donors$tr.est), exp(lo.coal.pw$num.donors$con.est))
lo.coal.pw$donations <- with(lo.coal.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$donations <- reais.format(mean(exp(lo.coal.pw$donations$tr.est) , exp(lo.coal.pw$donations$con.est)) / lo.coal.pw$num.donors)
lo.coal.pw$N <- nrow(lo.coal.pw.data)

##Public works, PT
lo.pt.pw <- with(lo.pt.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$est.unlogged <- reais.format(exp(lo.pt.pw$tr.est) - exp(lo.pt.pw$con.est))
lo.pt.pw$num.donors <- with(lo.pt.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$num.donors <- mean(exp(lo.pt.pw$num.donors$tr.est), exp(lo.pt.pw$num.donors$con.est))
lo.pt.pw$donations <- with(lo.pt.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = infl.vote.margin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$donations <- reais.format(mean(exp(lo.pt.pw$donations$tr.est) , exp(lo.pt.pw$donations$con.est)) / lo.pt.pw$num.donors)
lo.pt.pw$N <- nrow(lo.pt.pw.data)

###Local Linear
##All candidates
ll.all <- summaryR.lm(lm(log((contracts.0810 + 1)/donor.firms) ~ elected*infl.vote.margin , data = ll.all.data), type = "hc2")
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summaryR.lm(lm(log(donor.firms) ~ elected*infl.vote.margin , data = ll.all.data), type = "hc2")
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summaryR.lm(lm(log(donations) ~ elected*infl.vote.margin , data = ll.all.data), type = "hc2")
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*infl.vote.margin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*infl.vote.margin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*infl.vote.margin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*infl.vote.margin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*infl.vote.margin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*infl.vote.margin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*infl.vote.margin, data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*infl.vote.margin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*infl.vote.margin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

##All candidates
ply.all <- summaryR.lm(lm(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))   , data = ply.all.data))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summaryR.lm(lm(as.formula(paste("log(donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summaryR.lm(lm(as.formula(paste("log((donations)) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data)

##Public works
ply.all.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.data))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * infl.vote.margin + ", paste("I(infl.vote.margin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data)

##Gather all results into one table
infl.results.table <- data.frame(cbind(
  round(c(lo.all$est, lo.all.pw$est, lo.coal.pw$est, lo.pt.pw$est, ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(lo.all$se, lo.all.pw$se, lo.coal.pw$se, lo.pt.pw$se, ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c(lo.all$est.unlogged, lo.all.pw$est.unlogged, lo.coal.pw$est.unlogged, lo.pt.pw$est.unlogged, ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c(lo.all$donations, lo.all.pw$donations, lo.coal.pw$donations, lo.pt.pw$donations, ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(lo.all$N, lo.all.pw$N, lo.coal.pw$N, lo.pt.pw$N, ply.all$N, ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(infl.results.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity.  The loess specification uses a bandwidth of ", prettyNum(lo.bw, big.mark = ",", scientific = FALSE), " inflated votes and a span of ", span, ". The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " inflated votes, respectively.  Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

infl.results.table.latex <- latex(infl.results.table, cdec = c(2, 2, 0, 0, 0), file = "appendix_table4.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts Using Inflated Vote Margin", insert.bottom = bottom.note, rgroup = c("Loess Estimator", "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")


#####
#Figure 6: Balance Statistics using Standardized Vote Margin
#####
depfed_data$incumbent <- depfed.balance$incumbent
##Loess Data, Estimation Samples
lo.bw <- .007
lo.all.data <- depfed_data[abs(depfed_data$margin.nomvote)<lo.bw & depfed_data$donations>0,]
lo.all.pw.data <- depfed_data[abs(depfed_data$margin.nomvote)<lo.bw & depfed_data$pw.donations>0,]
lo.coal.pw.data <- depfed_data[abs(depfed_data$margin.nomvote)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.data <- depfed_data[abs(depfed_data$margin.nomvote)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Loess Data, Balance Samples
lo.all.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<lo.bw & depfed.balance$donations>0,]
lo.all.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<lo.bw & depfed.balance$pw.donations>0,]
lo.coal.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<lo.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<lo.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]

###Local Linear Bandwidth
ll.bw <- .003
##Local Linear Data, Estimation Samples
ll.all.data <- depfed_data[abs(depfed_data$margin.nomvote) < ll.bw & depfed_data$donations > 0,]
ll.all.pw.data <- depfed_data[abs(depfed_data$margin.nomvote)<ll.bw & depfed_data$pw.donations>0,]
ll.coal.pw.data <- depfed_data[abs(depfed_data$margin.nomvote)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.data <- depfed_data[abs(depfed_data$margin.nomvote)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Local Linear Data, Balance Samples
ll.all.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote) < ll.bw & depfed.balance$donations > 0,]
ll.all.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<ll.bw & depfed.balance$pw.donations>0,]
ll.coal.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<ll.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote)<ll.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]



##Polynomial Data, Estimation Samples
poly.order <- 3
ply.bw <- .03
ply.all.data <- depfed_data[abs(depfed_data$margin.nomvote) < ply.bw & depfed_data$donations > 0,]
ply.all.pw.data <- depfed_data[abs(depfed_data$margin.nomvote) < ply.bw & depfed_data$pw.donations>0,]
ply.coal.pw.data <- depfed_data[abs(depfed_data$margin.nomvote) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.data <- depfed_data[abs(depfed_data$margin.nomvote) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Polynomial Data, Balance Samples
ply.all.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote) < ply.bw & depfed.balance$donations > 0,]
ply.all.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote) < ply.bw & depfed.balance$pw.donations>0,]
ply.coal.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote) < ply.bw & depfed.balance$pw.donations>0 & depfed.balance$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.baldata <- depfed.balance[abs(depfed.balance$margin.nomvote) < ply.bw & depfed.balance$pw.donations>0 & depfed.balance$party == "PT",]

bal.var <- c("coalvotes", "incumbent", "contracts.0406", "pw.con.0406", "donations", "pw.donations", "donor.firms", "pw.donor.firms", "year.opened", "commerce", "manufacture", "financial", "cand.uf.sp", "cand.uf.mg", "cand.uf.rs", "cand.uf.ba", "cand.uf.rj", "party.psdb", "party.pfl", "party.pt", "party.pmdb", "superior.edu", "occ.pol", "yob", "individ.donations", "occ.business", "coalvotes", "individual.donors", "coalseats", "agriculture", "numb.company.recipients", "total.company.donations", "totalDonations.winners.firm", "winners.donated.to")

lo.bal <- list()
lo.bal$all <- list()
lo.bal$all.pw <- list()
lo.bal$coal.pw <- list()
lo.bal$pt.pw <- list()

dm.bal <- list()
dm.bal$all <- list()
dm.bal$all.pw <- list()
dm.bal$coal.pw <- list()
dm.bal$pt.pw <- list()


ll.bal <- list()
ll.bal$all <- list()
ll.bal$all.pw <- list()
ll.bal$coal.pw <- list()
ll.bal$pt.pw <- list()
length(ll.bal$pt.pw) <- length(bal.var)

ply.bal <- list()
ply.bal$all <- list()
ply.bal$all.pw <- list()
ply.bal$coal.pw <- list()
ply.bal$pt.pw <- list()
length(ply.bal$pt.pw) <- length(bal.var)

for(i in 1:length(bal.var)){
  print(paste("Checking Balance on", bal.var[i]))
  lo.bal$all[[i]] <- with(lo.all.baldata, lo.ate(y = lo.all.baldata[ , bal.var[i]], treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
  lo.bal$all[[i]]$sd <- (sd(lo.all.baldata[lo.all.baldata$elected == 1 , bal.var[i]]) + sd(lo.all.baldata[lo.all.baldata$elected == 0 , bal.var[i]])) / 2
  names(lo.bal$all)[i] <- bal.var[i]
  
  lo.bal$all.pw[[i]] <- with(lo.all.pw.baldata, lo.ate(y = lo.all.pw.baldata[, bal.var[i]], treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
  lo.bal$all.pw[[i]]$sd <- (sd(lo.all.pw.baldata[lo.all.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.all.pw.baldata[lo.all.pw.baldata$elected == 0 , bal.var[i]])) / 2
  names(lo.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(lo.coal.pw.baldata[ , bal.var[i]])) == 1){
    lo.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(lo.coal.pw.baldata[ , bal.var[i]])) > 1){
    lo.bal$coal.pw[[i]] <- with(lo.coal.pw.baldata, lo.ate(y = lo.coal.pw.baldata[, bal.var[i]], treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
    lo.bal$coal.pw[[i]]$sd <- (sd(lo.coal.pw.baldata[lo.coal.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.coal.pw.baldata[lo.coal.pw.baldata$elected == 0 , bal.var[i]])) / 2  
  }
  names(lo.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(lo.pt.pw.baldata[ , bal.var[i]])) == 1){
    lo.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(lo.pt.pw.baldata[ , bal.var[i]])) > 1){
    lo.bal$pt.pw[[i]] <- with(lo.pt.pw.baldata, lo.ate(y = lo.pt.pw.baldata[, bal.var[i]], treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
    lo.bal$pt.pw[[i]]$sd <- (sd(lo.pt.pw.baldata[lo.pt.pw.baldata$elected == 1 , bal.var[i]]) + sd(lo.pt.pw.baldata[lo.pt.pw.baldata$elected == 0 , bal.var[i]])) / 2
  }
  names(lo.bal$pt.pw)[i] <- bal.var[i]
  
  dm.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.all.baldata), type = "hc2")
  dm.bal$all[[i]]$sd <- (sd(dm.all.baldata[dm.all.baldata$elected == 1, bal.var[i]]) + sd(dm.all.baldata[dm.all.baldata$elected == 0, bal.var[i]])) / 2
  names(dm.bal$all)[i] <- bal.var[i]
  
  dm.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.all.pw.baldata), type = "hc2")
  dm.bal$all.pw[[i]]$sd <- (sd(dm.all.pw.baldata[dm.all.pw.baldata$elected == 1, bal.var[i]]) + sd(dm.all.pw.baldata[dm.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(dm.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(dm.coal.pw.baldata[ , bal.var[i]])) == 1){
    dm.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(dm.coal.pw.baldata[ , bal.var[i]])) > 1){
    dm.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.coal.pw.baldata), type = "hc2")
    dm.bal$coal.pw[[i]]$sd <- (sd(dm.coal.pw.baldata[dm.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(dm.coal.pw.baldata[dm.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(dm.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(dm.pt.pw.baldata[ , bal.var[i]])) == 1){
    dm.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(dm.pt.pw.baldata[ , bal.var[i]])) > 1){ 
    dm.bal$pt.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected")) , data = dm.pt.pw.baldata), type = "hc2")
    dm.bal$pt.pw[[i]]$sd <- (sd(dm.pt.pw.baldata[dm.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(dm.pt.pw.baldata[dm.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(dm.bal$pt.pw)[i] <- bal.var[i]
  
  ll.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*margin.nomvote")) , data = ll.all.baldata), type = "hc2")
  ll.bal$all[[i]]$sd <- (sd(ll.all.baldata[ll.all.baldata$elected == 1, bal.var[i]]) + sd(ll.all.baldata[ll.all.baldata$elected == 0, bal.var[i]])) / 2
  names(ll.bal$all)[i] <- bal.var[i]
  
  ll.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*margin.nomvote")) , data = ll.all.pw.baldata), type = "hc2")
  ll.bal$all.pw[[i]]$sd <- (sd(ll.all.pw.baldata[ll.all.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.all.pw.baldata[ll.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(ll.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(ll.coal.pw.baldata[ , bal.var[i]])) == 1){
    ll.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(ll.coal.pw.baldata[ , bal.var[i]])) > 1){
    ll.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*margin.nomvote")) , data = ll.coal.pw.baldata), type = "hc2")
    ll.bal$coal.pw[[i]]$sd <- (sd(ll.coal.pw.baldata[ll.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.coal.pw.baldata[ll.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(ll.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(ll.pt.pw.baldata[ , bal.var[i]])) == 1){
    ll.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(ll.pt.pw.baldata[ , bal.var[i]])) > 1){
    ll.bal$pt.pw[[i]] <- tryCatch(summaryR.lm(lm(formula(paste(bal.var[i], "~ elected*margin.nomvote")) , data = ll.pt.pw.baldata), type = "hc2"), error = function(e) NA)
    if(is.na(ll.bal$pt.pw[[i]][1]) == FALSE){
      ll.bal$pt.pw[[i]]$sd <- (sd(ll.pt.pw.baldata[ll.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(ll.pt.pw.baldata[ll.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
    }
  }
  names(ll.bal$pt.pw)[i] <- bal.var[i]  
  ply.bal$all[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.all.baldata), type = "hc2")
  ply.bal$all[[i]]$sd <- (sd(ply.all.baldata[ply.all.baldata$elected == 1, bal.var[i]]) + sd(ply.all.baldata[ply.all.baldata$elected == 0, bal.var[i]])) / 2
  names(ply.bal$all)[i] <- bal.var[i]
  
  ply.bal$all.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.all.pw.baldata), type = "hc2")
  ply.bal$all.pw[[i]]$sd <- (sd(ply.all.pw.baldata[ply.all.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.all.pw.baldata[ply.all.pw.baldata$elected == 0, bal.var[i]])) / 2
  names(ply.bal$all.pw)[i] <- bal.var[i]
  
  if(length(unique(ply.coal.pw.baldata[ , bal.var[i]])) == 1){
    ply.bal$coal.pw[[i]] <- NA
  }
  if(length(unique(ply.coal.pw.baldata[ , bal.var[i]])) > 1){
    ply.bal$coal.pw[[i]] <- summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.baldata), type = "hc2")
    ply.bal$coal.pw[[i]]$sd <- (sd(ply.coal.pw.baldata[ply.coal.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.coal.pw.baldata[ply.coal.pw.baldata$elected == 0, bal.var[i]])) / 2
  }
  names(ply.bal$coal.pw)[i] <- bal.var[i]
  
  if(length(unique(ply.pt.pw.baldata[ , bal.var[i]])) == 1){
    ply.bal$pt.pw[[i]] <- NA
  }
  if(length(unique(ply.pt.pw.baldata[ , bal.var[i]])) > 1){
    ply.bal$pt.pw[[i]] <- tryCatch(summaryR.lm(lm(formula(paste(bal.var[i], "~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.baldata), type = "hc2"), error = function(e) NA)
    if(is.na(ply.bal$pt.pw[[i]][1]) == FALSE){
      ply.bal$pt.pw[[i]]$sd <- (sd(ply.pt.pw.baldata[ply.pt.pw.baldata$elected == 1, bal.var[i]]) + sd(ply.pt.pw.baldata[ply.pt.pw.baldata$elected == 0, bal.var[i]])) / 2
    }
  }
  names(ply.bal$pt.pw)[i] <- bal.var[i]
  
}

lo.bal <- lapply(lo.bal, function(x){x[is.na(x)] <- NULL; x})
ll.bal <- lapply(ll.bal, function(x){x[is.na(x)] <- NULL; x})
dm.bal <- lapply(dm.bal, function(x){x[is.na(x)] <- NULL; x})
ply.bal <- lapply(ply.bal, function(x){x[is.na(x)] <- NULL; x})
std.diff.table <- data.frame(Estimate = c(
  ldply(lo.bal, function(x) ldply(x, function(x) x$est))$V1,
  ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1,
  ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1),
                             SD = c(
                               ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$V1,
                               ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$V1,
                               ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$V1),
                             Variable = c(
                               ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$.id,
                               ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$.id,
                               ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$.id),  
                             Sample = c(rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(lo.bal, length)), 
                                        rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), 
                                            sapply(ply.bal, length)),
                                        rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(ll.bal, length))
                             ),
                             Estimator = c(
                               rep("Loess", sum(sapply(lo.bal, length))), 
                               rep("Polynomial", sum(sapply(ply.bal, length))), rep("Local Linear", sum(sapply(ll.bal, length))))
)
std.diff.table$std.diff <- std.diff.table$Estimate / std.diff.table$SD
std.diff.table$Variable <- reorder(std.diff.table$Variable, std.diff.table$std.diff, mean)

tstat.table <- data.frame(Estimate = c(
  ldply(lo.bal, function(x) ldply(x, function(x) x$est))$V1,
  ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1,
  ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,1]))$V1),
                          SE = c(
                            ldply(lo.bal, function(x) ldply(x, function(x) x$se))$V1,
                            ldply(ply.bal, function(x) ldply(x, function(x) coef(x)[2,2]))$V1,
                            ldply(ll.bal, function(x) ldply(x, function(x) coef(x)[2,2]))$V1),
                          Variable = c(
                            ldply(lo.bal, function(x) ldply(x, function(x) x$sd))$.id,
                            ldply(ply.bal, function(x) ldply(x, function(x) x$sd))$.id,
                            ldply(ll.bal, function(x) ldply(x, function(x) x$sd))$.id),  
                          Sample = c(
                            rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(lo.bal, length)), 
                            rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(ply.bal, length)),
                            rep(c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT"), sapply(ll.bal, length))
                          ),
                          Estimator = c(
                            rep("Loess", sum(sapply(lo.bal, length))),
                            rep("Polynomial", sum(sapply(ply.bal, length))), rep("Local Linear", sum(sapply(ll.bal, length))))
)
tstat.table$tstat <- abs(tstat.table$Estimate / tstat.table$SE)
tstat.table$Variable <- reorder(tstat.table$Variable, tstat.table$tstat, max)
std.diff.table$Variable <- recode(std.diff.table$Variable, c("'coalvotes' = 'Coalition Votes'; 'yob' = 'Birth Year'; 'comm.donations' = 'Party Donations'; 'incumbent' = 'Incumbent'; 'contracts.0406' = 'Contracts (\\'04-\\'06)'; 'pw.con.0406' = 'Pub. Works Contracts (\\'04-\\'06)'; 'donations' = 'Total Donations Received'; 'pw.donations' = 'Pub. Works Donations Received'; 'donor.firms' = 'No. Donor Firms'; 'pw.donor.firms' = 'Pct. Pub. Works Donors'; 'year.opened' = 'Mean Donor Year Founded'; 'commerce' = 'Pct. Commerce Donors'; 'manufacture' = 'Pct. Manufacturing Donors'; 'financial' = 'Pct. Financial Donors'; 'agriculture' = 'Pct. Agricultural Donors'; 'cand.uf.sp' = 'State - São Paulo'; 'cand.uf.mg' = 'State - Minas Gerais';  'cand.uf.rs' = 'State - Rio Grande do Sul'; 'superior.edu' = 'Higher Education'; 'occ.pol' = 'Occupation - Politician'; 'individ.donations' = 'Individual Donations'; 'numb.company.recipients' = 'Mean Donor No. Candidate Receipients'; 'party.pmdb' = 'Party - PMDB'; 'party.pfl' = 'Party - PFL'; 'total.company.donations' = 'Mean Donor Total Donations'; 'coalvotes' = 'Coalition Votes'; 'party.pt' = 'Party - PT'; 'party.psdb' = 'Party - PSDB'; 'occ.business' = 'Occupation - Business'; 'cand.uf.rj' = 'State - Rio de Janeiro'; 'cand.uf.ba' = 'State - Bahia'; 'coalseats' = 'Coalition Seats'; 'individual.donors' = 'No. Individual Donors'; 'totalDonations.winners.firm' = 'Mean Donor Donations to Winners'; 'winners.donated.to' = 'Mean Donor No. Winning Recipients'"))
tstat.table$Variable <- recode(tstat.table$Variable, c("'coalvotes' = 'Coalition Votes'; 'yob' = 'Birth Year'; 'comm.donations' = 'Party Donations'; 'incumbent' = 'Incumbent'; 'contracts.0406' = 'Contracts (\\'04-\\'06)'; 'pw.con.0406' = 'Pub. Works Contracts (\\'04-\\'06)'; 'donations' = 'Total Donations Received'; 'pw.donations' = 'Pub. Works Donations Received'; 'donor.firms' = 'Donor Firms'; 'pw.donor.firms' = 'Pct. Pub. Works Donors'; 'year.opened' = 'Mean Donor Year Founded'; 'commerce' = 'Pct. Commerce Donors'; 'manufacture' = 'Pct. Manufacturing Donors'; 'financial' = 'Pct. Financial Donors'; 'agriculture' = 'Pct. Agricultural Donors'; 'cand.uf.sp' = 'State - São Paulo'; 'cand.uf.mg' = 'State - Minas Gerais';  'cand.uf.rs' = 'State - Rio Grande do Sul'; 'superior.edu' = 'Higher Education'; 'occ.pol' = 'Occupation - Politician'; 'individ.donations' = 'Individual Donations'; 'numb.company.recipients' = 'Mean Donor Candidate Receipients'; 'party.pmdb' = 'Party - PMDB'; 'party.pfl' = 'Party - PFL'; 'total.company.donations' = 'Mean Donor Total Donations'; 'coalvotes' = 'Coalition Votes'; 'party.pt' = 'Party - PT'; 'party.psdb' = 'Party - PSDB'; 'occ.business' = 'Occupation - Business'; 'cand.uf.rj' = 'State - Rio de Janeiro'; 'cand.uf.ba' = 'State - Bahia'; 'coalseats' = 'Coalition Seats'; 'individual.donors' = 'Individual Donors'; 'totalDonations.winners.firm' = 'Mean Donor Donations to Winners'; 'winners.donated.to' = 'Mean Donor Winning Recipients'"))
levels(std.diff.table$Sample) <- c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT")
levels(tstat.table$Sample) <- c("All", "Public Works", "Pub. Works, Coalition", "Pub. Works, PT")

pdf(file = "appendix_figure6.pdf", height = 6, width = 10)
ggplot(tstat.table, aes(x = tstat, y = Variable, shape = Sample, color = Sample)) + geom_point() + geom_vline(xintercept = 2, lty = 2, size = .2) + facet_grid(.~Estimator) + theme_bw() + scale_x_continuous("T Statistic") + scale_color_brewer(palette = "Set1") + opts(axis.title.x = theme_text(vjust = -0.3), title = "Balance Statistics for Federal Deputies")
dev.off()


##########
#Table 5: The Effect of Electoral Victory on Future Federal Government Contracts Using a Standardized (Nominal) Vote Margin
##########

#Loess Estimator
#All Donation Recipients
lo.all <-  with(lo.all.data, lo.ate(y = log((contracts.0810 + 1)/donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.all$est.unlogged <- reais.format(exp(lo.all$tr.est) - exp(lo.all$con.est))
lo.all$num.donors <- with(lo.all.data, lo.ate(y = log(donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.all$num.donors <- mean(exp(lo.all$num.donors$tr.est), exp(lo.all$num.donors$con.est))
lo.all$donations <- with(lo.all.data , lo.ate(y = log(donations), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.all$donations <- reais.format(mean(exp(lo.all$donations$tr.est) , exp(lo.all$donations$con.est)) / lo.all$num.donors)
lo.all$N <- nrow(depfed_data[abs(depfed_data$margin.nomvote) < lo.bw & depfed_data$donations>0,]) 

##Public Works, all
lo.all.pw <- with(lo.all.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$est.unlogged <- reais.format(exp(lo.all.pw$tr.est) - exp(lo.all.pw$con.est))
lo.all.pw$num.donors <- with(lo.all.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$num.donors <- mean(exp(lo.all.pw$num.donors$tr.est), exp(lo.all.pw$num.donors$con.est))
lo.all.pw$donations <- with(lo.all.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$donations <- reais.format(mean(exp(lo.all.pw$donations$tr.est) , exp(lo.all.pw$donations$con.est)) / lo.all.pw$num.donors)
lo.all.pw$N <- nrow(lo.all.pw.data)

##Public works, coalition
lo.coal.pw <- with(lo.coal.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$est.unlogged <- reais.format(exp(lo.coal.pw$tr.est) - exp(lo.coal.pw$con.est))
lo.coal.pw$num.donors <- with(lo.coal.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$num.donors <- mean(exp(lo.coal.pw$num.donors$tr.est), exp(lo.coal.pw$num.donors$con.est))
lo.coal.pw$donations <- with(lo.coal.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$donations <- reais.format(mean(exp(lo.coal.pw$donations$tr.est) , exp(lo.coal.pw$donations$con.est)) / lo.coal.pw$num.donors)
lo.coal.pw$N <- nrow(lo.coal.pw.data)

##Public works, PT
lo.pt.pw <- with(lo.pt.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$est.unlogged <- reais.format(exp(lo.pt.pw$tr.est) - exp(lo.pt.pw$con.est))
lo.pt.pw$num.donors <- with(lo.pt.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$num.donors <- mean(exp(lo.pt.pw$num.donors$tr.est), exp(lo.pt.pw$num.donors$con.est))
lo.pt.pw$donations <- with(lo.pt.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = margin.nomvote, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$donations <- reais.format(mean(exp(lo.pt.pw$donations$tr.est) , exp(lo.pt.pw$donations$con.est)) / lo.pt.pw$num.donors)
lo.pt.pw$N <- nrow(lo.pt.pw.data)

###Local Linear
##All candidates
ll.all <- summaryR.lm(lm(log((contracts.0810 + 1)/donor.firms) ~ elected*margin.nomvote , data = ll.all.data), type = "hc2")
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summaryR.lm(lm(log(donor.firms) ~ elected*margin.nomvote , data = ll.all.data), type = "hc2")
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summaryR.lm(lm(log(donations) ~ elected*margin.nomvote , data = ll.all.data), type = "hc2")
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*margin.nomvote , data = ll.all.pw.data), type = "hc2")
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*margin.nomvote , data = ll.all.pw.data), type = "hc2")
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*margin.nomvote , data = ll.all.pw.data), type = "hc2")
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*margin.nomvote , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*margin.nomvote , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*margin.nomvote , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*margin.nomvote, data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*margin.nomvote , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*margin.nomvote , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

##All candidates
ply.all <- summaryR.lm(lm(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))   , data = ply.all.data))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summaryR.lm(lm(as.formula(paste("log(donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summaryR.lm(lm(as.formula(paste("log((donations)) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data)

##Public works
ply.all.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.data))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * margin.nomvote + ", paste("I(margin.nomvote^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data)

##Gather all results into one table
nom.results.table <- data.frame(cbind(
  round(c(lo.all$est, lo.all.pw$est, lo.coal.pw$est, lo.pt.pw$est, ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(lo.all$se, lo.all.pw$se, lo.coal.pw$se, lo.pt.pw$se, ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c(lo.all$est.unlogged, lo.all.pw$est.unlogged, lo.coal.pw$est.unlogged, lo.pt.pw$est.unlogged, ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c(lo.all$donations, lo.all.pw$donations, lo.coal.pw$donations, lo.pt.pw$donations, ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(lo.all$N, lo.all.pw$N, lo.coal.pw$N, lo.pt.pw$N, ply.all$N, ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(nom.results.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity.  The loess specification uses a bandwidth of ", prettyNum(lo.bw * 100, big.mark = ",", scientific = FALSE), " percent of nominal votes and a span of ", span, ". The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw * 100 , big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw * 100, big.mark = ",", scientific = FALSE), " percent of nominal votes, respectively.  Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

nom.results.table.latex <- latex(nom.results.table, cdec = c(2, 2, 0, 0, 0), file = "appendix_table5.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts Using a Standardized (Nominal) Vote Margin", insert.bottom = bottom.note, rgroup = c("Loess Estimator", "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")


######
#Table 6: The Effect of Electoral Victory on Future Federal Government Contracts, Using Ranks as the Forcing Variable
######

##Loess Data, Estimation Samples
lo.bw <- 40000
lo.all.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$donations>0,]
lo.all.pw.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$pw.donations>0,]
lo.coal.pw.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
lo.pt.pw.data <- depfed_data[abs(depfed_data$votemargin)<lo.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

###Local Linear Bandwidth
ll.bw <- 25000
##Local Linear Data, Estimation Samples
ll.all.data <- depfed_data[abs(depfed_data$votemargin) < ll.bw & depfed_data$donations > 0,]
ll.all.pw.data <- depfed_data[abs(depfed_data$votemargin)<ll.bw & depfed_data$pw.donations>0,]
ll.coal.pw.data <- depfed_data[abs(depfed_data$votemargin)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ll.pt.pw.data <- depfed_data[abs(depfed_data$votemargin)<ll.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]

##Polynomial Data, Estimation Samples
poly.order <- 3
ply.bw <- 100000
ply.all.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$donations > 0,]
ply.all.pw.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$pw.donations>0,]
ply.coal.pw.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),]
ply.pt.pw.data <- depfed_data[abs(depfed_data$votemargin) < ply.bw & depfed_data$pw.donations>0 & depfed_data$party == "PT",]




##Loess Estimator
##All Donation Recipients
lo.all <-  with(lo.all.data, lo.ate(y = log((contracts.0810 + 1)/donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.all$est.unlogged <- reais.format(exp(lo.all$tr.est) - exp(lo.all$con.est))
lo.all$num.donors <- with(lo.all.data, lo.ate(y = log(donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.all$num.donors <- mean(exp(lo.all$num.donors$tr.est), exp(lo.all$num.donors$con.est))
lo.all$donations <- with(lo.all.data , lo.ate(y = log(donations), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.all$donations <- reais.format(mean(exp(lo.all$donations$tr.est) , exp(lo.all$donations$con.est)) / lo.all$num.donors)
lo.all$N <- nrow(depfed_data[abs(depfed_data$rank_discont) < lo.bw & depfed_data$donations>0,]) 

##Public Works, all
lo.all.pw <- with(lo.all.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$est.unlogged <- reais.format(exp(lo.all.pw$tr.est) - exp(lo.all.pw$con.est))
lo.all.pw$num.donors <- with(lo.all.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$num.donors <- mean(exp(lo.all.pw$num.donors$tr.est), exp(lo.all.pw$num.donors$con.est))
lo.all.pw$donations <- with(lo.all.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.all.pw$donations <- reais.format(mean(exp(lo.all.pw$donations$tr.est) , exp(lo.all.pw$donations$con.est)) / lo.all.pw$num.donors)
lo.all.pw$N <- nrow(lo.all.pw.data)

##Public works, coalition
lo.coal.pw <- with(lo.coal.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$est.unlogged <- reais.format(exp(lo.coal.pw$tr.est) - exp(lo.coal.pw$con.est))
lo.coal.pw$num.donors <- with(lo.coal.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$num.donors <- mean(exp(lo.coal.pw$num.donors$tr.est), exp(lo.coal.pw$num.donors$con.est))
lo.coal.pw$donations <- with(lo.coal.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw$donations <- reais.format(mean(exp(lo.coal.pw$donations$tr.est) , exp(lo.coal.pw$donations$con.est)) / lo.coal.pw$num.donors)
lo.coal.pw$N <- nrow(lo.coal.pw.data)

##Public works, PT
lo.pt.pw <- with(lo.pt.pw.data, lo.ate(y = log((pw.con.0810 + 1)/pw.donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$est.unlogged <- reais.format(exp(lo.pt.pw$tr.est) - exp(lo.pt.pw$con.est))
lo.pt.pw$num.donors <- with(lo.pt.pw.data, lo.ate(y = log(pw.donor.firms), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$num.donors <- mean(exp(lo.pt.pw$num.donors$tr.est), exp(lo.pt.pw$num.donors$con.est))
lo.pt.pw$donations <- with(lo.pt.pw.data , lo.ate(y = log(pw.donations), treat = elected, force.var = rank_discont, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw$donations <- reais.format(mean(exp(lo.pt.pw$donations$tr.est) , exp(lo.pt.pw$donations$con.est)) / lo.pt.pw$num.donors)
lo.pt.pw$N <- nrow(lo.pt.pw.data)

###Local Linear
##All candidates
ll.all <- summaryR.lm(lm(log((contracts.0810 + 1)/donor.firms) ~ elected*rank_discont, data = ll.all.data), type = "hc2")
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summaryR.lm(lm(log(donor.firms) ~ elected*rank_discont , data = ll.all.data), type = "hc2")
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summaryR.lm(lm(log(donations) ~ elected*rank_discont , data = ll.all.data), type = "hc2")
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*rank_discont, data = ll.all.pw.data), type = "hc2")
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*rank_discont , data = ll.all.pw.data), type = "hc2")
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*rank_discont , data = ll.all.pw.data), type = "hc2")
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*rank_discont, data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*rank_discont , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*rank_discont , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*rank_discont, data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*rank_discont , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*rank_discont , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

##All candidates
ply.all <- summaryR.lm(lm(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))   , data = ply.all.data))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summaryR.lm(lm(as.formula(paste("log(donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summaryR.lm(lm(as.formula(paste("log((donations)) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data)

##Public works
ply.all.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.pt.pw.data))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * rank_discont + ", paste("I(rank_discont^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data)

##Gather all results into one table
rank.results.table <- data.frame(cbind(
  round(c(lo.all$est, lo.all.pw$est, lo.coal.pw$est, lo.pt.pw$est, ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(lo.all$se, lo.all.pw$se, lo.coal.pw$se, lo.pt.pw$se, ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c(lo.all$est.unlogged, lo.all.pw$est.unlogged, lo.coal.pw$est.unlogged, lo.pt.pw$est.unlogged, ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c(lo.all$donations, lo.all.pw$donations, lo.coal.pw$donations, lo.pt.pw$donations, ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(lo.all$N, lo.all.pw$N, lo.coal.pw$N, lo.pt.pw$N, ply.all$N, ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(rank.results.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity.  The loess specification uses a bandwidth of ", prettyNum(lo.bw, big.mark = ",", scientific = FALSE), " votes and a span of ", span, ". The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " votes, respectively.  Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

rank.results.table.latex <- latex(rank.results.table, cdec = c(2, 2, 0, 0, 0), file = "appendix_table6.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts, Using Ranks as the Forcing Variable", insert.bottom = bottom.note, rgroup = c("Loess Estimator", "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")


#####
#Figure 7: The Effect of Electoral Victory on Future Government Contracts
#####
plot.all.0810 <- with(depfed_data[abs(depfed_data$votemargin)<40000 & depfed_data$donations>0,], discont.plot(y = log((contracts.0810 + 1)/donor.firms), force.var = votemargin, cluster = depfed.id, treat = elected, span = 1, degree = 1, bins = 20, xlab = "Raw Vote Margin", ylab = "log(mean contract + 1, 2008-2010)", title = "All Candidates"))+ guides(colour = guide_legend(title.hjust = 0.7)) 
plot.pw.0810 <- with(depfed_data[abs(depfed_data$votemargin)<40000 & depfed_data$pw.donations>0 ,], discont.plot(y = log((pw.con.0810 + 1)/donor.firms), force.var = votemargin, cluster = depfed.id, treat = elected, span = 1, degree = 1, bins = 20, xlab = "Raw Vote Margin", ylab = "log(mean contract + 1, 2008-2010)", title = "All Candidates with Public Works Donations")) 
plot.pw.coal.0810 <- with(depfed_data[abs(depfed_data$votemargin)<40000 & depfed_data$pw.donations>0 & depfed_data$party %in% c('PMDB','PP','PV','PSB','PC do B','PDT','PL','PRONA'),], discont.plot(y = log((pw.con.0810 + 1)/donor.firms), force.var = votemargin, cluster = depfed.id, treat = elected, span = 1, degree = 1, bins = 20, xlab = "Raw Vote Margin", ylab = "log(mean contract + 1, 2008-2010)", title = "Coalition Candidates with Public Works Donations")) 
plot.pw.pt.0810 <- with(depfed_data[abs(depfed_data$votemargin)<40000 & depfed_data$pw.donations>0 & depfed_data$party=='PT',], discont.plot(y = log((pw.con.0810 + 1)/donor.firms), force.var = votemargin, cluster = depfed.id, treat = elected, span = 1, degree = 1, bins = 20, xlab = "Raw Vote Margin", ylab = "log(mean contract + 1, 2008-2010)", title = "PT Candidates with Public Works Donations"))

vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
pdf("appendix_figure7.pdf", width=9, height=7)
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
print(plot.all.0810 + theme(axis.title.x = element_blank()) + theme(axis.text.x = element_blank(), axis.ticks = element_blank()), vp=vplayout(1,1))
print(plot.pw.0810 +  theme(axis.title.x = element_blank()) + theme(axis.text.x = element_blank(), axis.ticks = element_blank()), vp=vplayout(1,2))
print(plot.pw.coal.0810, vp=vplayout(2,1))
print(plot.pw.pt.0810, vp=vplayout(2,2))
dev.off()

######
#Figure 8: Placebo Estimates: The effect on contracts for public works donors to PT candidates of a treatment defined using placebo thresholds.
#####

cutpoints <- seq(-15000, 15000, 7500)
lo.placebo.effects <- rep(NA, length(cutpoints))
lo.placebo.se <- rep(NA, length(cutpoints))
ply.placebo.effects <- rep(NA, length(cutpoints))
ply.placebo.se <- rep(NA, length(cutpoints))
ll.placebo.effects <- rep(NA, length(cutpoints))
ll.placebo.se <- rep(NA, length(cutpoints))

for(i in 1:length(cutpoints)){
  lo.pt.pw.data$fake.vote.margin <- lo.pt.pw.data$votemargin - cutpoints[i]
  lo.pt.pw.data$placebo <- ifelse(lo.pt.pw.data$fake.vote.margin > 0, 1, 0)
  lo.placebo.results <-  with(lo.pt.pw.data, lo.ate(y = log((pw.con.0810 + 1) / donor.firms), treat = placebo, force.var =  fake.vote.margin, span = span, R = num.boots, degree = lo.degree))
  lo.placebo.effects[i] <- lo.placebo.results$est
  lo.placebo.se[i] <- lo.placebo.results$se
  
  ply.placebo.data <- depfed_data[depfed_data$pw.donations>0 & depfed_data$party == "PT",]
  ply.placebo.data$fake.vote.margin <- ply.placebo.data$votemargin - cutpoints[i]
  ply.placebo.data$placebo <- ifelse(ply.placebo.data$fake.vote.margin > 0, 1, 0)
  ply.placebo.data <- ply.placebo.data[abs(ply.placebo.data$fake.vote.margin) < ply.bw,]  
  ply.placebo.results <-  summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ placebo * fake.vote.margin + ", paste("I(fake.vote.margin^", 2:poly.order, ") * placebo", sep ="", collapse = " + "))) , data = ply.placebo.data))
  ply.placebo.effects[i] <- coef(ply.placebo.results)[2, 1]
  ply.placebo.se[i] <- coef(ply.placebo.results)[2, 2]
  
  ll.placebo.data <- depfed_data[depfed_data$pw.donations>0 & depfed_data$party == "PT",]
  ll.placebo.data$fake.vote.margin <- ll.placebo.data$votemargin - cutpoints[i]
  ll.placebo.data$placebo <- ifelse(ll.placebo.data$fake.vote.margin > 0, 1, 0)
  ll.placebo.data <- ll.placebo.data[abs(ll.placebo.data$fake.vote.margin) < ll.bw,]  
  ll.placebo.results <-  summaryR.lm(lm(log((pw.con.0810 + 1) / donor.firms) ~ placebo*fake.vote.margin, data = ll.placebo.data), type = "hc2")
  ll.placebo.effects[i] <- coef(ll.placebo.results)[2, 1]
  ll.placebo.se[i] <- coef(ll.placebo.results)[2, 2]
}

shifted.placebos <- rbind(
  data.frame(Threshold = cutpoints, Estimate = ply.placebo.effects, "T Statistic" = ply.placebo.effects / ply.placebo.se, Estimator = "Polynomial"), 
  data.frame(Threshold = cutpoints, Estimate = lo.placebo.effects, "T Statistic" = lo.placebo.effects / lo.placebo.se, Estimator = "Loess"), data.frame(Threshold = cutpoints, Estimate = ll.placebo.effects, "T Statistic" = ll.placebo.effects / ll.placebo.se, Estimator = "Local Linear"))
shifted.placebos <- melt(shifted.placebos, measure.vars = c("Estimate", "T.Statistic"))

pdf(file = "appendix_figure8.pdf", height = 8, width = 7)
ggplot(shifted.placebos, aes(x = Threshold, y = value, color = Estimator, shape = Estimator)) + geom_point(size = 3) + geom_vline(xintercept = 0, linetype = 2, size = .2) + geom_hline(yintercept = 0, linetype = 2, size = .2) + scale_color_brewer(palette = "Set1") + theme_bw() + facet_grid(variable ~ ., scales = "free") + scale_y_continuous("Statistic") + scale_x_continuous(breaks = cutpoints)
dev.off()


#######
#Table 7: The Effect of Electoral Victory on Future Federal Government Contracts for Donors to Other Candidates
#######

#All Contracts received by other donors
#Loess Estimator
#All Donation Recipients
lo.all.falsif <-  with(lo.all.data, lo.ate(y = log((donoronly02.contracts0810 + 1)), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.falsif$est.unlogged <- reais.format(exp(lo.all.falsif$tr.est) - exp(lo.all.falsif$con.est))
lo.all.falsif$N <- nrow(depfed_data[abs(depfed_data$votemargin) < lo.bw & depfed_data$donations>0,]) 

##Public Works, all
lo.all.pw.falsif <- with(lo.all.pw.data, lo.ate(y = log((nondonors.pwcontracts + 1)), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.all.pw.falsif$est.unlogged <- reais.format(exp(lo.all.pw.falsif$tr.est) - exp(lo.all.pw.falsif$con.est))
lo.all.pw.falsif$N <- nrow(lo.all.pw.data)

##Public works, coalition
lo.coal.pw.falsif <- with(lo.coal.pw.data, lo.ate(y = log((nondonors.pwcontracts + 1)), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.coal.pw.falsif$est.unlogged <- reais.format(exp(lo.coal.pw.falsif$tr.est) - exp(lo.coal.pw.falsif$con.est))
lo.coal.pw.falsif$N <- nrow(lo.coal.pw.data)

##Public works, PT
lo.pt.pw.falsif <- with(lo.pt.pw.data, lo.ate(y = log((nondonors.pwcontracts + 1)), treat = elected, force.var = votemargin, span = span, R = num.boots, degree = lo.degree))
lo.pt.pw.falsif$est.unlogged <- reais.format(exp(lo.pt.pw.falsif$tr.est) - exp(lo.pt.pw.falsif$con.est))
lo.pt.pw.falsif$N <- nrow(lo.pt.pw.data)

### Polynomial
##All candidates
ply.all.falsif <- summaryR.lm(lm(as.formula(paste("log((donoronly02.contracts0810 + 1)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all.falsif$est <- coef(ply.all.falsif)[2,1]
ply.all.falsif$se <- coef(ply.all.falsif)[2,2]
ply.all.falsif$est.unlogged <- reais.format(exp(coef(ply.all.falsif)[1,1] + coef(ply.all.falsif)[2,1]) - exp(coef(ply.all.falsif)[1,1]))
ply.all.falsif$N <- nrow(ply.all.data)

##Public works
ply.all.pw.falsif<-summaryR.lm(lm(as.formula(paste("log((nondonors.pwcontracts + 1)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw.falsif$est <- coef(ply.all.pw.falsif)[2,1]
ply.all.pw.falsif$se <- coef(ply.all.pw.falsif)[2,2]
ply.all.pw.falsif$est.unlogged <- reais.format(exp(coef(ply.all.pw.falsif)[1,1] + coef(ply.all.pw.falsif)[2,1]) - exp(coef(ply.all.pw.falsif)[1,1]))
ply.all.pw.falsif$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw.falsif<-summaryR.lm(lm(as.formula(paste("log((nondonors.pwcontracts + 1)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw.falsif$est <- coef(ply.coal.pw.falsif)[2,1]
ply.coal.pw.falsif$se <- coef(ply.coal.pw.falsif)[2,2]
ply.coal.pw.falsif$est.unlogged <- reais.format(exp(coef(ply.coal.pw.falsif)[1,1] + coef(ply.coal.pw.falsif)[2,1]) - exp(coef(ply.coal.pw.falsif)[1,1]))
ply.coal.pw.falsif$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw.falsif<-summaryR.lm(lm(as.formula(paste("log((nondonors.pwcontracts + 1)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data), type = "hc2")
ply.pt.pw.falsif$est <- coef(ply.pt.pw.falsif)[2,1]
ply.pt.pw.falsif$se <- coef(ply.pt.pw.falsif)[2,2]
ply.pt.pw.falsif$est.unlogged <- reais.format(exp(coef(ply.pt.pw.falsif)[1,1] + coef(ply.pt.pw.falsif)[2,1]) - exp(coef(ply.pt.pw.falsif)[1,1]))
ply.pt.pw.falsif$N <- nrow(ply.pt.pw.data)


###Local Linear
##All candidates
ll.all.falsif <- summaryR.lm(lm(log((donoronly02.contracts0810 + 1)) ~ elected*votemargin , data = ll.all.data), type = "hc2")
ll.all.falsif$est <- coef(ll.all.falsif)[2,1]
ll.all.falsif$se <- coef(ll.all.falsif)[2,2]
ll.all.falsif$est.unlogged <- reais.format(exp(coef(ll.all.falsif)[1,1] + coef(ll.all.falsif)[2,1]) - exp(coef(ll.all.falsif)[1,1]))
ll.all.falsif$N <- nrow(ll.all.data)

##Public works
ll.all.pw.falsif <- summaryR.lm(lm(log((nondonors.pwcontracts + 1)) ~ elected*votemargin , data = ll.all.pw.data), type = "hc2")
ll.all.pw.falsif$est <- coef(ll.all.pw.falsif)[2,1]
ll.all.pw.falsif$se <- coef(ll.all.pw.falsif)[2,2]
ll.all.pw.falsif$est.unlogged <- reais.format(exp(coef(ll.all.pw.falsif)[1,1] + coef(ll.all.pw.falsif)[2,1]) - exp(coef(ll.all.pw.falsif)[1,1]))
ll.all.pw.falsif$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw.falsif <- summaryR.lm(lm(log((nondonors.pwcontracts + 1)) ~ elected*votemargin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw.falsif$est <- coef(ll.coal.pw.falsif)[2,1]
ll.coal.pw.falsif$se <- coef(ll.coal.pw.falsif)[2,2]
ll.coal.pw.falsif$est.unlogged <- reais.format(exp(coef(ll.coal.pw.falsif)[1,1] + coef(ll.coal.pw.falsif)[2,1]) - exp(coef(ll.coal.pw.falsif)[1,1]))
ll.coal.pw.falsif$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw.falsif <- summaryR.lm(lm(log((nondonors.pwcontracts + 1)) ~ elected*votemargin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw.falsif$est <- coef(ll.pt.pw.falsif)[2,1]
ll.pt.pw.falsif$se <- coef(ll.pt.pw.falsif)[2,2]
ll.pt.pw.falsif$est.unlogged <- reais.format(exp(coef(ll.pt.pw.falsif)[1,1] + coef(ll.pt.pw.falsif)[2,1]) - exp(coef(ll.pt.pw.falsif)[1,1]))
ll.pt.pw.falsif$N <- nrow(ll.pt.pw.data)


##Gather all results into one table
falsif.table <- data.frame(cbind(
  round(c(lo.all.falsif$est, lo.all.pw.falsif$est, lo.coal.pw.falsif$est, lo.pt.pw.falsif$est, ply.all.falsif$est, ply.all.pw.falsif$est, ply.coal.pw.falsif$est, ply.pt.pw.falsif$est,  ll.all.falsif$est, ll.all.pw.falsif$est, ll.coal.pw.falsif$est, ll.pt.pw.falsif$est), 2),
  round(c(lo.all.falsif$se, lo.all.pw.falsif$se, lo.coal.pw.falsif$se, lo.pt.pw.falsif$se, ply.all.falsif$se, ply.all.pw.falsif$se, ply.coal.pw.falsif$se, ply.pt.pw.falsif$se, ll.all.falsif$se, ll.all.pw.falsif$se, ll.coal.pw.falsif$se, ll.pt.pw.falsif$se),2),
  c(lo.all.falsif$est.unlogged, lo.all.pw.falsif$est.unlogged, lo.coal.pw.falsif$est.unlogged, lo.pt.pw.falsif$est.unlogged, ply.all.falsif$est.unlogged, ply.all.pw.falsif$est.unlogged, ply.coal.pw.falsif$est.unlogged, ply.pt.pw.falsif$est.unlogged, ll.all.falsif$est.unlogged, ll.all.pw.falsif$est.unlogged, ll.coal.pw.falsif$est.unlogged, ll.pt.pw.falsif$est.unlogged),
  c(lo.all.falsif$N, lo.all.pw.falsif$N, lo.coal.pw.falsif$N, lo.pt.pw.falsif$N, ply.all.falsif$N, ply.all.pw.falsif$N, ply.coal.pw.falsif$N, ply.pt.pw.falsif$N, ll.all.falsif$N, ll.all.pw.falsif$N, ll.coal.pw.falsif$N, ll.pt.pw.falsif$N)
))

names(falsif.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged" , "N"  )
bottom.note <- paste("Dependent variable is the log of the total value of contracts (plus one) received by corporate donors to other candidates, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. The loess specification uses a bandwidth of ", prettyNum(lo.bw, big.mark = ",", scientific = FALSE), " votes and a span of ", span, ". The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " votes, respectively.  Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

falsif.table.latex <- latex(falsif.table, cdec = c(2, 2, 0, 0), file = "appendix_table7.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts for Donors to Other Candidates", insert.bottom = bottom.note, rgroup = c("Loess Estimator", "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")

##########
#Table 8: The Effect of Electoral Victory on Future Federal Government Contracts (Covariate Adjusted)
##########
demean <- function(x){x - mean(x)}
covariates <- "demean(incumbent) + demean(log(contracts.0406 + 1)) + demean(log(pw.con.0406 + 1)) + demean(log(donations)) + demean(donor.firms) + demean(pw.donor.firms) + demean(log(pw.donations + 1))"
##All candidates

# RESULTS

###Local Linear
##All candidates
ll.all <- summaryR.lm(lm(log((contracts.0810 + 1)/donor.firms) ~ elected*votemargin  + demean(incumbent) + demean(log(contracts.0406 + 1)) + demean(log(pw.con.0406 + 1)) + demean(log(donations)) + demean(donor.firms) + demean(pw.donor.firms) + demean(log(pw.donations + 1)), data = ll.all.data), type = "hc2")
ll.all$est <- coef(ll.all)[2,1]
ll.all$se <- coef(ll.all)[2,2]
ll.all$est.unlogged <- reais.format(exp(coef(ll.all)[1,1] + coef(ll.all)[2,1]) - exp(coef(ll.all)[1,1]))
ll.all$num.donors <- summaryR.lm(lm(log(donor.firms) ~ elected*votemargin , data = ll.all.data), type = "hc2")
ll.all$num.donors <- mean(exp(coef(ll.all$num.donors)[1,1]), exp(coef(ll.all$num.donors)[1,1] + coef(ll.all$num.donors)[2,1] ))
ll.all$donations <- summaryR.lm(lm(log(donations) ~ elected*votemargin , data = ll.all.data), type = "hc2")
ll.all$donations <- reais.format( mean(exp(coef(ll.all$donations)[1,1]), exp(coef(ll.all$donations)[1,1] + coef(ll.all$donations)[2,1])))
ll.all$N <- nrow(ll.all.data)

##Public works
ll.all.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin + demean(incumbent) + demean(log(contracts.0406 + 1)) + demean(log(pw.con.0406 + 1)) + demean(log(donations)) + demean(donor.firms) + demean(pw.donor.firms) + demean(log(pw.donations + 1)), data = ll.all.pw.data), type = "hc2")
ll.all.pw$est <- coef(ll.all.pw)[2,1]
ll.all.pw$se <- coef(ll.all.pw)[2,2]
ll.all.pw$est.unlogged <- reais.format(exp(coef(ll.all.pw)[1,1] + coef(ll.all.pw)[2,1]) - exp(coef(ll.all.pw)[1,1]))
ll.all.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$num.donors <- mean(exp(coef(ll.all.pw$num.donors)[1,1]), exp(coef(ll.all.pw$num.donors)[1,1] + coef(ll.all.pw$num.donors)[2,1] ))
ll.all.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.all.pw.data), type = "hc2")
ll.all.pw$donations <- reais.format( mean(exp(coef(ll.all.pw$donations)[1,1]), exp(coef(ll.all.pw$donations)[1,1] + coef(ll.all.pw$donations)[2,1])))
ll.all.pw$N <- nrow(ll.all.pw.data)

##Coalition, public works
ll.coal.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin + demean(incumbent) + demean(log(contracts.0406 + 1)) + demean(log(pw.con.0406 + 1)) + demean(log(donations)) + demean(donor.firms) + demean(pw.donor.firms) + demean(log(pw.donations + 1)), data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$est <- coef(ll.coal.pw)[2,1]
ll.coal.pw$se <- coef(ll.coal.pw)[2,2]
ll.coal.pw$est.unlogged <- reais.format(exp(coef(ll.coal.pw)[1,1] + coef(ll.coal.pw)[2,1]) - exp(coef(ll.coal.pw)[1,1]))
ll.coal.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$num.donors <- mean(exp(coef(ll.coal.pw$num.donors)[1,1]), exp(coef(ll.coal.pw$num.donors)[1,1] + coef(ll.coal.pw$num.donors)[2,1] ))
ll.coal.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.coal.pw.data), type = "hc2")
ll.coal.pw$donations <- reais.format( mean(exp(coef(ll.coal.pw$donations)[1,1]), exp(coef(ll.coal.pw$donations)[1,1] + coef(ll.coal.pw$donations)[2,1])))
ll.coal.pw$N <- nrow(ll.coal.pw.data)

##PT. public works
ll.pt.pw <- summaryR.lm(lm(log((pw.con.0810 + 1)/pw.donor.firms) ~ elected*votemargin + demean(incumbent) + demean(log(contracts.0406 + 1)) + demean(log(pw.con.0406 + 1)) + demean(log(donations)) + demean(donor.firms) + demean(pw.donor.firms) + demean(log(pw.donations + 1)), data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$est <- coef(ll.pt.pw)[2,1]
ll.pt.pw$se <- coef(ll.pt.pw)[2,2]
ll.pt.pw$est.unlogged <- reais.format(exp(coef(ll.pt.pw)[1,1] + coef(ll.pt.pw)[2,1]) - exp(coef(ll.pt.pw)[1,1]))
ll.pt.pw$num.donors <- summaryR.lm(lm(log(pw.donor.firms) ~ elected*votemargin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$num.donors <- mean(exp(coef(ll.pt.pw$num.donors)[1,1]), exp(coef(ll.pt.pw$num.donors)[1,1] + coef(ll.pt.pw$num.donors)[2,1] ))
ll.pt.pw$donations <- summaryR.lm(lm(log(pw.donations) ~ elected*votemargin , data = ll.pt.pw.data), type = "hc2")
ll.pt.pw$donations <- reais.format( mean(exp(coef(ll.pt.pw$donations)[1,1]), exp(coef(ll.pt.pw$donations)[1,1] + coef(ll.pt.pw$donations)[2,1])))
ll.pt.pw$N <- nrow(ll.pt.pw.data)

###Higher Order Polynomial Specification

ply.all <- summaryR.lm(lm(as.formula(paste("log((contracts.0810 + 1)/donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected",  sep ="", collapse = " + "), " + ", covariates, sep = ""))   , data = ply.all.data))
ply.all$est <- coef(ply.all)[2,1]
ply.all$se <- coef(ply.all)[2,2]
ply.all$est.unlogged <- reais.format(exp(coef(ply.all)[1,1] + coef(ply.all)[2,1]) - exp(coef(ply.all)[1,1]))
ply.all$num.donors <- summaryR.lm(lm(as.formula(paste("log(donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$num.donors <- mean(exp(coef(ply.all$num.donors)[1,1]), exp(coef(ply.all$num.donors)[1,1] + coef(ply.all$num.donors)[2,1] ))
ply.all$donations <- summaryR.lm(lm(as.formula(paste("log((donations)) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.data), type = "hc2")
ply.all$donations <- reais.format( mean(exp(coef(ply.all$donations)[1,1]), exp(coef(ply.all$donations)[1,1] + coef(ply.all$donations)[2,1])))
ply.all$N <- nrow(ply.all.data)

##Public works
ply.all.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), " + ", covariates, sep = ""))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$est <- coef(ply.all.pw)[2,1]
ply.all.pw$se <- coef(ply.all.pw)[2,2]
ply.all.pw$est.unlogged <- reais.format(exp(coef(ply.all.pw)[1,1] + coef(ply.all.pw)[2,1]) - exp(coef(ply.all.pw)[1,1]))
ply.all.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$num.donors <- mean(exp(coef(ply.all.pw$num.donors)[1,1]), exp(coef(ply.all.pw$num.donors)[1,1] + coef(ply.all.pw$num.donors)[2,1] ))
ply.all.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.all.pw.data), type = "hc2")
ply.all.pw$donations <- reais.format( mean(exp(coef(ply.all.pw$donations)[1,1]), exp(coef(ply.all.pw$donations)[1,1] + coef(ply.all.pw$donations)[2,1])))
ply.all.pw$N <- nrow(ply.all.pw.data)

##Coalition, public works
ply.coal.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), " + ", covariates, sep = ""))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$est <- coef(ply.coal.pw)[2,1]
ply.coal.pw$se <- coef(ply.coal.pw)[2,2]
ply.coal.pw$est.unlogged <- reais.format(exp(coef(ply.coal.pw)[1,1] + coef(ply.coal.pw)[2,1]) - exp(coef(ply.coal.pw)[1,1]))
ply.coal.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$num.donors <- mean(exp(coef(ply.coal.pw$num.donors)[1,1]), exp(coef(ply.coal.pw$num.donors)[1,1] + coef(ply.coal.pw$num.donors)[2,1] ))
ply.coal.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))) , data = ply.coal.pw.data), type = "hc2")
ply.coal.pw$donations <- reais.format( mean(exp(coef(ply.coal.pw$donations)[1,1]), exp(coef(ply.coal.pw$donations)[1,1] + coef(ply.coal.pw$donations)[2,1])))
ply.coal.pw$N <- nrow(ply.coal.pw.data)

##PT. public works
ply.pt.pw <- summaryR.lm(lm(as.formula(paste("log((pw.con.0810 + 1)/pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "), " + ", covariates, sep = "")) , data = ply.pt.pw.data))
ply.pt.pw$est <- coef(ply.pt.pw)[2,1]
ply.pt.pw$se <- coef(ply.pt.pw)[2,2]
ply.pt.pw$est.unlogged <- reais.format(exp(coef(ply.pt.pw)[1,1] + coef(ply.pt.pw)[2,1]) - exp(coef(ply.pt.pw)[1,1]))
ply.pt.pw$num.donors <- summaryR.lm(lm(as.formula(paste("log(pw.donor.firms) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + ")))  , data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$num.donors <- mean(exp(coef(ply.pt.pw$num.donors)[1,1]), exp(coef(ply.pt.pw$num.donors)[1,1] + coef(ply.pt.pw$num.donors)[2,1] ))
ply.pt.pw$donations <- summaryR.lm(lm(as.formula(paste("log(pw.donations) ~ elected * votemargin + ", paste("I(votemargin^", 2:poly.order, ") * elected", sep ="", collapse = " + "))), data = ply.pt.pw.data), type = "hc2")
ply.pt.pw$donations <- reais.format( mean(exp(coef(ply.pt.pw$donations)[1,1]), exp(coef(ply.pt.pw$donations)[1,1] + coef(ply.pt.pw$donations)[2,1])))
ply.pt.pw$N <- nrow(ply.pt.pw.data)

##Gather all results into one table
covadj.results.table <- data.frame(cbind(
  round(c(ply.all$est, ply.all.pw$est, ply.coal.pw$est, ply.pt.pw$est,  ll.all$est, ll.all.pw$est, ll.coal.pw$est, ll.pt.pw$est), 2),
  round(c(ply.all$se, ply.all.pw$se, ply.coal.pw$se, ply.pt.pw$se, ll.all$se, ll.all.pw$se, ll.coal.pw$se, ll.pt.pw$se),2),
  c( ply.all$est.unlogged, ply.all.pw$est.unlogged, ply.coal.pw$est.unlogged, ply.pt.pw$est.unlogged, ll.all$est.unlogged, ll.all.pw$est.unlogged, ll.coal.pw$est.unlogged, ll.pt.pw$est.unlogged),
  c( ply.all$donations, ply.all.pw$donations, ply.coal.pw$donations, ply.pt.pw$donations, ll.all$donations, ll.all.pw$donations, ll.coal.pw$donations, ll.pt.pw$donations),
  c(ply.all$N,  ply.all.pw$N, ply.coal.pw$N, ply.pt.pw$N, ll.all$N, ll.all.pw$N, ll.coal.pw$N, ll.pt.pw$N)
))


names(covadj.results.table) <- c("$\\tau_{RD}$", "SE", "$\\tau_{RD}$, unlogged", "Mean Donation" , "N"  )
bottom.note <- paste("Dependent variable is the log of the average value of contracts (plus one) received by a candidate's corporate donors, January 2008--September 2010. ``Coalition'' candidates are those from the PMDB, PP, PV, PSB, PC do B, PDT, PL, and PRONA in 2006. The unlogged treatment effect is given by $exp(E[Y_{ij}(1)|M_{ij} =0]) - exp(E[Y_{ij}(0)|M_{ij} =0])$. ``Mean Donation'' is the estimated donation per firm for candidates at the discontinuity. The local linear and polynomial specifications use bandwidths of ", prettyNum(ll.bw, big.mark = ",", scientific = FALSE), " and ", prettyNum(ply.bw, big.mark = ",", scientific = FALSE), " votes, respectively. Loess standard errors are bootstrapped; others are heteroskedasticity-robust.", sep = "")

covadj.results.table.latex <- latex(covadj.results.table, cdec = c(2, 2, 0, 0, 0), file = "appendix_table8.tex", col.just = rep("c", 5), rowname = c("All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT", "All", "Pub. works donations", "Pub. works, coalition", "Pub. works, PT" ), rowlabel = "Sample", caption = "The Effect of Electoral Victory on Future Federal Government Contracts (Covariate Adjusted)", insert.bottom = bottom.note, rgroup = c( "Polynomial Estimator", "Local Linear Estimator"), n.rgroup = c(4, 4 ), booktabs = FALSE, ctable = TRUE, where = "htp")


#####
#Figure 9: Portfolio investment among public works firms, 2006.
#####

numerator <- with(portfolio_invest_data, tapply(as.numeric(party=="PT")*elected*donations*21, cnpj14, sum))
denom <- with(portfolio_invest_data, tapply(donations, cnpj14, sum))
e1 <- numerator/denom

lnumerator <- with(portfolio_invest_data, tapply(as.numeric(party=="PT")*elected*(log(donations)*8.91), cnpj14, sum))
ldenom <- with(portfolio_invest_data, tapply(log(donations), cnpj14, sum))
e2 <- lnumerator-ldenom

unlnumerator <- with(portfolio_invest_data, tapply(as.numeric(party=="PT")*elected*exp(log(donations)*8.91), cnpj14, sum))
e3 <- unlnumerator/denom

portfolio_invest_data$num.cands <- NULL
nc <- data.frame(num.cands=with(portfolio_invest_data, tapply(elected, cnpj14, length)))
portfolio_invest_data <- merge(portfolio_invest_data, nc, by.x="cnpj14", by.y=0, all=TRUE)

port <- cbind(nc, 
              public=with(portfolio_invest_data, tapply(public.works, cnpj14, unique)),
              returns=e1,
              logreturns=e2,
              unlogreturns=e3,
              total.donated=denom)

effNum <- function (x) {
  x <- na.omit(x)/sum(x, na.rm=TRUE)
  return(1/sum(x^2))
}
port$effective.num.cands <- with(portfolio_invest_data, tapply(donations, cnpj14, effNum))


pdf("appendix_figure9.pdf", height=6, width=6)
with(port[port$public==1,], 
     hist(effective.num.cands, 
          #            main="Portfolio investment among public works firms, 2006",
          main="",
          xlab="Effective number of federal deputy candidate recipients",
          col="#dddddd",
          freq=F,
          breaks=40,
          ylim=0:1))
dev.off()
